使用Python将文件名保存在txt文件中

2024-05-17 03:44:58 发布

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

我有一个包含许多文件的目录,我想将这些文件的名称保存在txt文档中。我将用几个目录来做这件事,所以我想添加下面的名称,但是随着代码的创建,我删除了新目录已经保存的文件

这是我的代码:

os.chdir("/Users/Desktop/Data")

a = open("Names_Genomes.txt", "w")

for path, subdirs, files in os.walk(r'/Users/Desktop/control/input/end'):
    for filename in files:
        f = os.path.join(path, filename)
        a.write(str(f) + os.linesep) 

我还保存了目录,但我不想这样

/Users/Desktop/control/input/end/SRR3160442_bin.7.fna
/Users/Desktop/control/input/end/SRR1039533_bin.14.fna
/Users/Desktop/control/input/end/SRR6257496_bin.3.fna
/Users/Desktop/control/input/end/ERR1305905_bin.7.fna

谁能告诉我我做错了什么


Tags: 文件path代码目录txt名称forinput
3条回答

如果只想保存文件名而不保存绝对文件路径,则必须删除以下行:

f = os.path.join(path, filename)

最终代码必须类似于:

os.chdir("/Users/Desktop/Data")

a = open("Names_Genomes.txt", "w")

for path, subdirs, files in os.walk(r'/Users/Desktop/control/input/end'):
    for filename in files:
        a.write(str(filename) + os.linesep)

使用Python将2个目录中的文件名并排保存在txt文件中

导入操作系统

path="/content/HRNet-Semantic-Segmentation/imgs/images"  
path2 ="/content/HRNet-Semantic-Segmentation/imgs/masks"

a = open("/content/train.txt", "w")
    
    for path, subdirs, files in os.walk(path):
        for filename in files:
            f = os.path.join(path, filename)
    
        for filename2 in files:
            f2 = os.path.join(path2, filename2)
    
            a.write(str(f+" "+f2) + os.linesep) 

输出:

/content/imgs/images/frame_7450.jpg /content/imgs/masks/frame_7150.jpg
/content/imgs/images/frame_7450.jpg /content/imgs/masks/frame_13645.jpg
/content/imgs/images/frame_7450.jpg /content/imgs/masks/frame_4635.jpg
/content/imgs/images/frame_7450.jpg /content/imgs/masks/frame_8510.jpg
/content/imgs/images/frame_7450.jpg /content/imgs/masks/frame_5720.jpg
/content/imgs/images/frame_7450.jpg /content/imgs/masks/frame_13820.jpg
/content/imgs/images/frame_7450.jpg /content/imgs/masks/frame_7675.jpg
/content/imgs/images/frame_7450.jpg /content/imgs/masks/frame_4765.jpg
/content/imgs/images/frame_7450.jpg /content/imgs/masks/frame_7715.jpg

为了只写文件名,您应该删除绝对路径的连接。只需执行以下操作:

os.chdir("/Users/Desktop/Data")

a = open("Names_Genomes.txt", "a")

for path, subdirs, files in os.walk(r'/Users/Desktop/control/input/end'):
    for filename in files:
        a.write(filename + os.linesep) 

请记住,我将open()命令中的模式更改为a,而不是“w”,它不会覆盖数据,但会附加数据

相关问题 更多 >