我的代码有问题。我正在尝试替换文件中的模式。首先我在打开文件的数量上有错误,因为我忘记关闭我的文件。但是现在,我在我的代码中加入了 f.close() 并且出现以下错误:
ValueError: I/O operation on closed file.
在这里你可以找到我的代码的一部分。有人知道出了什么问题吗?
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import re
import shutil
from tempfile import mkstemp
infile = 'test_file.txt'
year = int('2009')
month = int('1')
day = int('10')
#################################################################################
def sed(pattern, replace, source):
"""
Reads a source file and writes the destination file.
In each line, replaces pattern with replace.
Args:
pattern (str): pattern to match (can be re.pattern)
replace (str): replacement str
source (str): input filename
"""
fin = open(source, 'r')
fd, name = mkstemp()
fout = open(name, 'w')
for line in fin:
out = re.sub(pattern, replace, line)
fout.write(out)
fin.close()
fout.close()
shutil.move(name, source)
#################################################################################
def main():
"""
Replace all year-month-days which have a possible wrong pattern
"""
for i in range (6):
for j in range (12):
for k in range (22):
Year = year + i; Month = month + j; Day = day + k
pattern = '%s %s%s' %(Year, Month, Day)
replace = '%s %s %s' %(Year, Month, Day)
sed(pattern, replace, infile)
#################################################################################
if __name__ == "__main__":
main()
###### END
万分感谢。
我将此作为另一个答案发布,因为它显然不同。
由于您的sed
函数打开太多文件时遇到问题,我尝试编写一些尽可能少地打开文件的内容。而且,你说你要编辑的文件很大,所以我避免直接读到内存中。
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import re
input_file = 'test_file.txt'
output_file = 'result_file.txt'
def main():
pattern = r"(\d{4}) (\d{1,2})(\d{2})"
replace = r"\1 \2 \3"
with open(input_file, "r") as inp:
with open(output_file, "w") as oup:
for line in inp:
sub = re.sub(pattern, replace, line)
oup.write(sub)
if __name__ == "__main__":
main()
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句