[英]Reading multiple log files from a folder using python
过去,我使用 python 读取了一个日志文件,代码如下,一直运行良好:
with open(r"24T23.log") as f, open('logfile.csv', 'w') as f2:
writer = csv.writer(f2)
writer.writerow(['Index','Date', 'Time', 'Logic', '(Logic)','Type', 'Code','Connector', 'Message', 'Extra 1', 'Extra 2'])
i = 0
for line in f:
writer.writerow([i] + line.rstrip().split('\t'))
i += 1
对于我正在处理的特定用例,我需要读取一个文件夹中包含的多个文件。 有人可以建议如何修改上面的代码(我尝试使用 blob 但未能成功)? 提前致谢。
这个怎么样?
import csv
import os
# From root of cwd
DIRECTORY = 'test'
# This gets the path of every file in DIRECTORY if it is a log file
# os.path.join(os.getcwd(),x) to include cwd in directory name
logs = [os.path.join(os.getcwd(), x) for x in os.listdir(
DIRECTORY) if os.path.splitext(x)[1] == '.log']
for log in logs:
# Note the 'a' append write, to append the rows to the files
with open(log) as f, open('logfile.csv', 'a') as f2:
writer = csv.writer(f2)
writer.writerow(['Index', 'Date', 'Time', 'Logic', '(Logic)',
'Type', 'Code', 'Connector', 'Message', 'Extra 1', 'Extra 2'])
i = 0
for line in f:
writer.writerow([i] + line.rstrip().split('\t'))
i += 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.