我有一行脚本,它可以获取目录和子目录中的所有.mblend文件,并将它们的路径写入文件。我希望每一行都有一个的起始前缀
">
但它不起作用。当我在我也需要的行尾添加前缀时,它就起作用了。
for root, dirs, files in os.walk(cwd):
for file in files:
if file.endswith('.blend'):
with open("filepaths","a+") as f:
f.write(os.path.join('"', root, file, '",' "n"))
此输出
/home/django/copypaste/cleanup/var/media/admin/94bbcd25-10a2-4ec2-bd83-a7cef0690320/splash279/splash279.blend/",
/home/django/copypaste/cleanup/var/media/admin/94bbcd25-10a2-4ec2-bd83-a7cef0690320/splash279/lib/props/barbershop_pole.blend/",
/home/django/copypaste/cleanup/var/media/admin/94bbcd25-10a2-4ec2-bd83-a7cef0690320/splash279/lib/props/hairdryer.blend/",
/home/django/copypaste/cleanup/var/media/admin/94bbcd25-10a2-4ec2-bd83-a7cef0690320/splash279/lib/chars/pigeon.blend/",
/home/django/copypaste/cleanup/var/media/admin/94bbcd25-10a2-4ec2-bd83-a7cef0690320/splash279/lib/chars/agent.blend/",
/home/django/copypaste/cleanup/var/media/admin/94bbcd25-10a2-4ec2-bd83-a7cef0690320/splash279/lib/nodes/nodes_shaders.blend/",
/home/django/copypaste/cleanup/var/media/admin/94bbcd25-10a2-4ec2-bd83-a7cef0690320/splash279/tools/camera_rig.blend/",
但它在行的开头缺少"
的第一个前缀
简单修复:
f.write(f'"{os.path.join(root, file)}",n')) # python 3.6+
f.write('"{}",n'.format(os.path.join(root, file)))) # python 2.7+
测试:
import os
for root, dirs, files in os.walk("./"):
for file in files:
# if file.endswith('.blend'): # have no blends
with open("filepaths","a+") as f:
f.write(f'"{os.path.join(root, file)}",n') # 3.6
f.write('"{}",n'.format(os.path.join(root, file))) # 2.7
with open("filepaths" ) as f:
print(f.read())
输出(在dir中只得到一个文件,将其写入文件两次(3.6+2.7((:
"./main.py",
"./main.py",
不知道为什么你的不起作用。。。这适用于3.6:
import os
for i in range(5):
with open(f"{i}.blend","w") as f:
f.write(" ")
with open(f"{i}.txt","w") as f:
f.write(" ")
for root, dirs, files in os.walk("./"):
for file in files:
if file.endswith('.blend'):
with open("filepaths","a+") as f:
f.write(os.path.join('"', root, file, '",' "n"))
else:
print("Not a blend: ", file)
with open("filepaths") as f:
print(f.read())
输出:
Not a blend: 0.txt
Not a blend: main.py
Not a blend: 1.txt
Not a blend: 4.txt
Not a blend: 3.txt
Not a blend: 2.txt
"/./3.blend/",
"/./2.blend/",
"/./4.blend/",
"/./1.blend/",
"/./0.blend/",