例如,
文件夹X内部有文件夹A,B和C,其中包含每个文件。
如何创建一个将进入每个Fodler A,B和C的循环,并在写入模式下打开我需要的文件进行一些更改?
答案 0 :(得分:0)
要修改遍历其子目录的不同文件的内容,可以使用os.walk和fnmatch - 选择要修改的正确文件格式!
import os, fnmatch
def modify_file(filepath):
try:
with open(filepath) as f:
s = f.read()
s = your_method(s) # return modified content
if s:
with open(filepath, "w") as f: #write modified content to same file
print filepath
f.write(s)
f.flush()
f.close()
except:
import traceback
print traceback.format_exc()
def modifyFileInDirectory(directory, filePattern):
for path, dirs, files in os.walk(os.path.abspath(directory), followlinks=True):
for filename in fnmatch.filter(files, filePattern):
modify_file(filename)
modifyFileInDirectory(your_path,file_patter)
答案 1 :(得分:0)
如果所有文件都具有相同的名称(例如result.txt
),则循环非常简单:
for subdir in ('A', 'B', 'C'):
path = 'X/{}/result.txt'.format(subdir)
with open(path, 'w') as fp:
fp.write("This is the result!\n")
或者,或许:
import os.path
for subdir in ('A', 'B', 'C'):
path = os.path.join('X', subdir, 'result.txt')
with open(path, 'w') as fp:
fp.write("This is the result!\n")
根据评论中列出的其他要求,我建议您使用glob.glob()
,如下所示:
import os.path
import glob
for subdir in glob.glob("X/certain*"):
path = os.path.join(subdir, "result.txt")
with open(path, 'w') as fp:
fp.write("This is the result\n")
在上面的示例中,对glob.glob()
的调用将返回以文字文本“确定”开头的X的所有子目录的列表。因此,这个循环可以连续创建“X / certainA / result.txt”和“X / certainBigHouse / result.txt”,假设这些子目录已经存在。