python 读取全部文件名以及路径,并且输出到txt

import os
txtName = "test.txt"
f=file(txtName, "a+")
dire="/media/tina/ET/caffe/SegNet_ip/CamVid/test/"
anchor="/media/tina/ET/caffe/SegNet_ip/CamVid/testannot/"
for root ,dirs, files in os.walk(dire):
    for file_single in files:
        test = dire+file_single
        refile = file_single[0:8]
        anchort = anchor + refile +'.png'
        result = test + " " +anchort +'\n'
        f.write( result)
f.close()

没写绝对路径,就会被认为是在当前文件夹,这个代码主要是研究生阶段各种实验用,我从两个功能代码拼接的。当然可能有更简洁美观的,欢迎留言交流。root里面存了绝对路径,不过由于我之后还要改,空格后面同一行的绝对路径,以及文件格式,所以直接写出来了。

这就是把待标注的图像以及标签写到同一个txt。包括了他们的绝对路径。用的挺多的。

这个代码会输出这样的txt:

python 读取全部文件名以及路径,并且输出到txt