用f.seek(0)在文件开头写入

时间:2019-06-11 13:07:44

标签: python-3.x

我正在调整输出文件的格式。我希望在文件的开头打印“总数为...”文本(因为我可能以数千行结尾)。目前,它正在文件的最后打印它。

我已经打开了()同时具有'a'和'w'。当我使用'w'时,它将搜索到开头,但是它将覆盖文本而不是移动文本。当我使用'a'时,output.seek(0,0)不会移到开头。

count = 0
with open('found_%s_or_not.txt' % replaceString, 'a') as output:
    for root, subdir, files in os.walk(scanFolder):
        for file in files:                                  

            if os.path.join(file).endswith('.mpr'):                             

                fullpath = os.path.join(root, file)

                with open(fullpath, 'r') as f:
                    for lines in file:
                        line = f.read()                                         
                        if replaceString in line:                     
                            output.write(os.path.join(root, file) + ' contains ' + replaceString + '\n') 
                            count = count + 1
    output.seek(0, 0)
    output.write('The total count is ' + str(count) + '\n\n')

我希望它看起来像这样:

The total count is 2

c:\spam contains bacon 

c:\pig contains bacon

目前我正在得到这个:

c:\spam contains bacon

c:\pig contains bacon

The total count is 2

1 个答案:

答案 0 :(得分:0)

而不是尝试以增量方式添加到文件中,请尝试列出行,然后一次将它们全部写入:

output_list = []
with open('found_%s_or_not.txt' % replaceString, 'w') as output:
    for root, subdir, files in os.walk(scanFolder):
        ...                             
                        if replaceString in line:                     
                            output_list.append(os.path.join(root, file) + ' contains ' + replaceString + '\n') 
        ...
    output_list = ['The total count is ' + str(count) + '\n\n'] + output_list
    output.write(''.join(output_list))