我在一行脚本中捕获了目录和子目录中的所有.blend文件,并将其路径写入文件。我希望每行的起始前缀都是
”
但是它不起作用。当我在需要的行末添加前缀时,它也可以工作。
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/",
但是在行首缺少"
的第一个前缀
答案 0 :(得分:2)
简单修复:
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)到file):
"./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/",