![](/img/trans.png)
[英]saving file names into a txt file and copying files into a directory query
[英]Saving files names in a txt file with 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
谁能告诉我我做错了什么?
如果您只想保存文件名而不是绝对文件路径,则必须删除该行:
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',这不会覆盖您的数据,但会 append 它。
将来自 2 个目录的文件名与 Python 并排保存在 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)
output:
/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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.