问题描述
我有一个目录,其中包含数百个文件夹,子文件夹以及子文件夹(在Windows中)的子文件夹。
我只是想在所有这些文件夹中创建一个小的txt文件,其单词为“ test”。
我已经尝试过类似的操作,但是无法使其正常工作:
for i in root_dir:
filename = "test.txt"
with open(filename,"w") as f:
f.write("Test")
attempt2
#only makes one file in the root directory - no sub directories though
import os
root_path8 = r'C:\Users\max\Downloads\users_visual\mgr8\mgr7\mgr6'
for i in next(os.walk(root_path8))[1]:
# print(j)
print(i)
root_dir = root_path8
filename = "test.txt"
filepath = os.path.join(root_dir,filename)
if not os.path.exists(root_dir):
os.makedirs(root_dir)
f = open(filepath,"a")
f.write("Test")
f.close()
解决方法
使用walk
获取目录中的所有子文件夹和子文件夹等。该迭代返回3个值(当前文件夹,子文件夹,文件);将第一个值传递给open
,使用os.path.join
连接文件夹名称和文件名称。例如
import os
folder_iter = os.walk(root_dir)
for current_folder,_,_ in folder_iter:
filename = "test.txt"
with open(os.path.join(current_folder,filename),"w") as f:
f.write("Test")
顺便说一句,如果在每种情况下它都是相同的文件,即您不需要分别创建每个文件,则可能更有效的方法是创建一个文件开始,然后将其复制到迭代中的每个文件夹中。