【发布时间】:2016-05-31 08:59:04
【问题描述】:
我需要一个 python 脚本来计算一个目录中所有文本文件中的行数,并生成一份关于具有 n 行数的文件数的一般报告。
报告应如下所示:
Files with 1 line: 636
Files with 2 lines: 346
Files with 3 lines: 234
Files with 4 lines: 723
Files with 5 lines: 254
Files with 6 lines: 223
Files with 7 lines: 1464
etc.
我找到了这个脚本,用于计算目录中所有文件中的行数 Python script to count num lines in all files in directory:
#!/usr/bin/env python
import csv
import copy
import os
import sys
import glob
#get current working dir, set count, and select file delimiter
os.chdir('/mydirectory')
#parses through files and saves to a dict
names={}
for fn in glob.glob('*.txt'):
with open(fn) as f:
names[fn]=sum(1 for line in f if line.strip() and not line.startswith('#'))
print names
#save the dictionary with key/val pairs to a csv
with open('seriescount.csv', 'wb') as f:
w = csv.DictWriter(f, names.keys())
sum(names.values())
我们如何生成一个像上面这样的简单报告? 谢谢。
【问题讨论】:
-
你有一个例子。所以开始工作,不要问。
-
与其搜索不能解决问题的低质量脚本,不如尝试学习 python 并编写自己的脚本。
-
虽然我同意这个问题是边缘性的,但 Stack Overflow 的基线不是“建立关于编程的可搜索和公共利益文章的百科全书”,而是“提出问题,得到答案,不分心”。这个问题尊重这一理念,并且比大多数单行“请为我解决我的问题”问题表现出更多的研究努力。
-
你们说的很对,我应该在问之前更加努力。只是有时我们需要解决特定问题才能继续进行其他/更大的项目。学习需要时间,但我们也通过分析目前对我们来说太难的问题的答案来学习。感谢@Jivan,我现在就这样做。