刚接触python,想批量读取txt文件的某行,从网上找了段代码,能成功跑出来,但没有生成汇总好的新文件,部分代码也看不懂,求大神教我怎么保存运行结果至新的txt或者csv,感谢!
import os
def eachFile(filepath):
pathDir =os.listdir(filepath) #遍历文件夹中的text
return pathDir
def readfile(name):
fopen=open(name, encoding='gb18030')
for lines in fopen.readlines(): #按行读取text中的内容
lines = lines.replace("\n", "").split(",")
if '57511' in str(lines):
print(lines)
if '57512' in str(lines):
print(lines)
if '57513' in str(lines):
print(lines)
if '57514' in str(lines):
print(lines)
if '57516' in str(lines):
print(lines)
fopen.close()
filePath = "E:/AHYH_data/vis-20200119-0219"
pathDir=eachFile(filePath)
for allDir in pathDir:
# child = os.path.join('%s%s' % (filepath, allDir))
child = "E:/AHYH_data/vis-20200119-0219" + '\\' + allDir
readfile(child)
以下是运行的部分结果
[' 57511 106.45 29.85 240 5.1', '20021922']
[' 57512 106.27 29.97 364 8.6', '20021922']
[' 57513 106.63 29.73 464 9.1', '20021922']
[' 57514 106.22 29.58 331 5.2', '20021922']
[' 57516 106.47 29.58 259 5.3', '20021922']
[' 57511 106.45 29.85 240 4.8', '20021923']
[' 57512 106.27 29.97 364 7.2', '20021923']
[' 57513 106.63 29.73 464 9.1', '20021923']
[' 57514 106.22 29.58 331 6.0', '20021923']
[' 57516 106.47 29.58 259 5.2', '20021923']