Python 在嵌套for循环中在位修改文件
我迭代其中的目录和文件,同时就地修改每个文件。我希望在之后立即读取新修改的文件。 以下是我的代码和描述性注释:Python 在嵌套for循环中在位修改文件,python,python-3.x,for-loop,in-place,Python,Python 3.x,For Loop,In Place,我迭代其中的目录和文件,同时就地修改每个文件。我希望在之后立即读取新修改的文件。 以下是我的代码和描述性注释: # go through each directory based on their ids for id in id_list: id_dir = os.path.join(ouput_dir, id) os.chdir(id_dir) # go through all files (with a specific extension) for fi
# go through each directory based on their ids
for id in id_list:
id_dir = os.path.join(ouput_dir, id)
os.chdir(id_dir)
# go through all files (with a specific extension)
for filename in glob('*' + ext):
# modify the file by replacing all new-line characters with an empty space
with fileinput.FileInput(filename, inplace=True) as f:
for line in f:
print(line.replace('\n', ' '), end='')
# here I would like to read the NEW modified file
with open(filename) as newf:
content = newf.read()
目前,newf
不是新修改的,而是原始的f
。我想我理解这是为什么,但是我发现很难克服这个问题
我总是可以进行两次单独的迭代(根据每个目录的ID,遍历所有文件(具有特定扩展名)并修改文件,然后重复迭代以读取每个文件),但我希望是否有更有效的方法。也许可以在修改后重新启动第二个for
循环,然后执行读取
(以避免至少重复外部for
循环)
有什么想法/设计可以用干净高效的方式实现上述目标吗?我并不是说你这样做是不正确的,但我觉得你把它复杂化了。这是我的超级简单的解决方案
import glob, fileinput
for filename in glob('*' + ext):
f_in = (x.rstrip() for x in open(filename, 'rb').readlines()) #instead of trying to modify in place we instead read in data and replace raw_values.
with open(filename, 'wb') as f_out: # we then write the data stream back out
#extra modification to the data can go here, i just remove the /r and /n and write back out
for i in f_in:
f_out.write(i)
#now there is no need to read the data back in because we already have a static referance to it.
对我来说,它适用于以下代码:
#!/usr/bin/env python3
import os
from glob import glob
import fileinput
id_list=['1']
ouput_dir='.'
ext = '.txt'
# go through each directory based on their ids
for id in id_list:
id_dir = os.path.join(ouput_dir, id)
os.chdir(id_dir)
# go through all files (with a specific extension)
for filename in glob('*' + ext):
# modify the file by replacing all new-line characters with an empty space
for line in fileinput.FileInput(filename, inplace=True):
print(line.replace('\n', ' ') , end="")
# here I would like to read the NEW modified file
with open(filename) as newf:
content = newf.read()
print(content)
注意我是如何迭代这些行的 您只打印替换的值,从不更改它
line.replace()
返回一行的新实例,并且不会覆盖原始实例?@TheLazyScript我刚刚纠正了一个小错误。除此之外,执行替换的代码块工作正常;i、 e.如果我单独尝试,它会修改并保存文件。您是否尝试过将print(line.replace('\n',''),end='')替换为line=line.replace('\n','');打印(行)
?您是否尝试过在f:
循环中的行的末尾使用f.write()
和f.close()
保存文件?@JanZeiseweis否,它不起作用。另外,我不明白额外的print
语句的作用。