我正在迭代其中的目录和文件,同时就地修改每个文件。我期待着有新修改的文件被读取后的权利。 以下是我的代码和描述性注释:
# 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
循环,然后使read
发生(这样至少可以避免重复外部for
循环)。你知道吗
有什么想法/设计能以干净高效的方式实现上述目标?你知道吗
我并不是说你这样做的方式是不正确的,但我觉得你把它复杂化了。这是我的超级简单的解决方案。你知道吗
对我来说,它适用于以下代码:
注意我是如何迭代这些行的!你知道吗
相关问题 更多 >
编程相关推荐