写入文件循环问题

时间:2015-07-12 23:34:35

标签: python for-loop

我遇到的问题是,只是将读取文件的所有行写入输出,只有最后一行在输出文件中。我相信它一遍又一遍地写,但我似乎无法告诉如何修复循环。如果有人能帮助我,我们将不胜感激。这个问题可能是在for循环中重复打开我的文件。

import os
import re

# 1.walk around directory and find lastjob.txt file in one of folders
rootDir = "C:\\Users\Bob\Desktop\Path Parsing Project"
for path, dirs, files in os.walk(rootDir):
for filename in files:
    fullpath = os.path.join(path, filename)
    if filename=="text.txt":
        # 2.open file. read from file
        fi = open(fullpath, 'r')
        # 3.parse text in incoming file and use regex to find PATH
        for line in fi:
            m = re.search("(Adding file.*)",line)
            if m:
                #4.write path and info to outgoing file
                #print(line)
                fo = open('outputFile', 'w')
                fo.write(line + '\n')

1 个答案:

答案 0 :(得分:1)

通过将fo = open('outputFile', 'w')放在开头,我得到了所需的结果,脚本处理得更快。

import os
import re
fo = open('outputFile', 'w')
# 1.walk around directory and find lastjob.txt file in one of folders
rootDir = "C:\\Users\Bob\Desktop\Path Parsing Project"
for path, dirs, files in os.walk(rootDir):
for filename in files:
    fullpath = os.path.join(path, filename)
    if filename=="text.txt":
        # 2.open file. read from file
        fi = open(fullpath, 'r')
        # 3.parse text in incoming file and use regex to find PATH
        for line in fi:
            m = re.search(r'(Adding file.*)',line)
            if m:
                fo.write(line)
fo.close()
fi.close()