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



我有一个目录,里面有很多文件,我想把这些文件的名称保存在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

有人能告诉我我做错了什么吗?

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

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)

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

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",它不会覆盖您的数据,但会附加它。

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

导入os

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

最新更新