每行開頭添加前綴 doesn

2024-04-25 23:51:53 发布

您现在位置:Python中文网/ 问答频道 /正文

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

但它缺少行开头的第一个前缀"


Tags: 文件djangohomeforadminvarlibmedia
1条回答
网友
1楼 · 发布于 2024-04-25 23:51:53

简单修复:

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/",

相关问题 更多 >