Python 追加文件应该用新数据刷新

Python Append file should refreshed with new data

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

    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