Python Append文件应该用新数据刷新



我正试图将我的输出写入一个文件,我的代码所做的是寻找匹配的文件名,并将其存储到一个类似于不匹配文件的文件中,但问题是,当我使用write时,它会覆盖文件,当我每次运行时使用append时,它都会继续追加文件匹配的文件名称。我需要的是,每当脚本运行时,它都会刷新te文件,并只加载当前数据。

import re
import sys
import os
import glob
import pandas as pd
import logging

try:
for file in glob.glob('*.csv'):
r = re.search(r'abc_sales_(20[0-9][0-9])-([1-9]|1[0-2]|0[0-9])-([1-9]|1[0-9]|2[0-9]|3[0-1]|0[0-9])-[0-9]{2}_[a-z0-9]{3,5}.csv', file)
if r:
#matched=file
print(f'File matched:{file}')
fp=open('bad_lines.txt', 'r+')
sys.stdout = fp

else:
path=f'File not matched:{file}'
f=open('filenotmatched.txt','a')
f.seek(0)
f.truncate()
f.write(path+'n')
f.close()
except Exception as e:
pass

建议对代码进行更改。

import re
import sys
import os
import glob
import pandas as pd
import logging
# We create new 'bad_lines.txt' and 
# 'filenotmatched.txt' for each run
with open('bad_lines.txt', 'w') as f_badlines, open('filenotmatched.txt','w') as f_notmatched:
try:
for file in glob.glob('*.csv'):
r = re.search(r'abc_sales_(20[0-9][0-9])-([1-9]|1[0-2]|0[0-9])-([1-9]|1[0-9]|2[0-9]|3[0-1]|0[0-9])-[0-9]{2}_[a-z0-9]{3,5}.csv', file)
if r:
#matched=file
#print(f'File matched:{file}')
#fp=open('bad_lines.txt', 'r+')
# ** Not clear why you redirected 
# ** standard out to a file
# ** rather than writing to file directly
#sys.stdout = fp
f_badlines.write(f'File matched:{file}n')
else:
path=f'File not matched:{file}'
#f=open('filenotmatched.txt','a')
#f.seek(0)
#f.truncate()
#f.write(path+'n')
#f.close()
f_notmatched.write(path + 'n')
except Exception as e:
pass

最新更新