我有一个python脚本(下面)应该在文本文件中找到以00和20开头的行,然后将行输出到两个单独的文件,一个用于00,一个用于20.它可以正常工作output1,但为output2生成一个空元组。我究竟做错了什么?文本文件中的行都是相同的,没有特殊字符,它以00或20开头。
import sys
import re
import glob
import os
listfiles = glob.glob('*.txt')
def DataExtract(inputfilename):
myfilename1 = open('00 extract ' + inputfilename,'w')
myfilename2 = open('20 extract ' + inputfilename,'w')
with open(inputfilename, 'r') as f:
output1 = re.findall(r'^00.*', f.read(), re.MULTILINE)
output2 = re.findall(r'^20.*', f.read(), re.MULTILINE)
wout1 = "\n".join(output1)
wout2 = "\n".join(output2)
print (wout2)
print (output2)
myfilename1.write(wout1)
myfilename2.write(wout2)
myfilename1.close
myfilename2.close
for n in listfiles:
DataExtract(n)
请帮忙!谢谢。
答案 0 :(得分:2)
第二次调用f.read()
时,没有什么可读的,因为第一个f.read()
alread消耗了文件流。因此,如果您将文件读入变量然后使用它而不是f.read()
,则可以解决问题,但由于您正在使用文字文本,因此您也可以逐行读取文件并使用str.startswith()
支票:
def DataExtract(inputfilename):
myfilename1 = open('00 extract ' + inputfilename,'w')
myfilename2 = open('20 extract ' + inputfilename,'w')
with open(inputfilename, 'r') as f:
for line in f:
if line.startswith('00'):
myfilename1.write(line)
elif line.startswith('20'):
myfilename2.write(line)
myfilename1.close()
myfilename2.close()