gpt4 book ai didi

python - 在每行开头添加前缀不起作用

转载 作者:行者123 更新时间:2023-12-01 01:22:00 25 4
gpt4 key购买 nike

我有一行脚本,它抓取目录和子目录中的所有 .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/",

但行首缺少第一个前缀 "

最佳答案

简单修复:

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())

输出(仅在目录中得到一个文件,将其写入文件两次(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/",

关于python - 在每行开头添加前缀不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53729454/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com