用于计算目录中所有文件中的num行的Python脚本
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了用于计算目录中所有文件中的num行的Python脚本,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2296字,纯文字阅读大概需要4分钟。
内容图文
所以我是python的新手,我正在尝试编写一个遍历目录中所有.txt文件的脚本,计算每个文件中的行数(除了空白或注释掉的行),然后写入最终输出到csv.最终输出应该如下所示:
agprices, avi, adp
132, 5, 8
我在使用语法时遇到问题,将每个计数保存为字典的值.这是我的代码如下:
#!/usr/bin/env python
import csv
import copy
import os
import sys
#get current working dir, set count, and select file delimiter
d = os.getcwd()
count = 0
ext = '.txt'
#parses through files and saves to a dict
series_dict = {}
txt_files = [i for i in os.listdir(d) if os.path.splitext(i)[1] == ext]
#selects all files with .txt extension
for f in txt_files:
with open(os.path.join(d,f)) as file_obj:
series_dict[f] = file_obj.read()
if line.strip(): #Exclude blank lines
continue
else if line.startswith("#"): #Exclude commented lines
continue
else
count +=1
#Need to save count as val in dict here
#save the dictionary with key/val pairs to a csv
with open('seriescount.csv', 'wb') as f:
w = csv.DictWriter(f, series_dict.keys())
w.writeheader()
w.writerow(series_dict)
所以这是编辑:
#!/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('/Users/Briana/Documents/Misc./PythonTest')
#parses through files and saves to a dict
series = {}
for fn in glob.glob('*.txt'):
with open(fn) as f:
series[fn] = (1 for line in f if line.strip() and not line.startswith('#'))
print series
#save the dictionary with key/val pairs to a csv
with open('seriescount.csv', 'wb') as f:
w = csv.DictWriter(f, series.keys())
sum(names.values())
我在第二行到最后一行收到缩进错误,我不确定为什么?另外,我并不认为我在最后一部分正确编写语法.再一次,我只是想在{a:132,b:245,c:13}这样的文件中返回一个包含文件名和行数的字典.
解决方法:
你可以尝试这些方面:
os.chdir(ur_directory)
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
那将打印一个类似于的字典:
{'test_text.txt': 20, 'f1.txt': 3, 'lines.txt': 101, 'foo.txt': 6, 'dat.txt': 6, 'hello.txt': 1, 'f2.txt': 4, 'neglob.txt': 8, 'bar.txt': 6, 'test_reg.txt': 6, 'mission_sp.txt': 71, 'test_nums.txt': 8, 'test.txt': 7, '2591.txt': 8303}
你可以在csv.DictWriter中使用那个Python dict.
如果你想要这些的总和,那就做:
sum(names.values())
内容总结
以上是互联网集市为您收集整理的用于计算目录中所有文件中的num行的Python脚本全部内容,希望文章能够帮你解决用于计算目录中所有文件中的num行的Python脚本所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。