Python-遍历文件名写入txt或csv

用python遍历文件名,读取导出到txt/csv文件中,参考代码如下。

import os
import csv
import glob

# img_path1 = glob.glob('/media/dell/2T/new/image1/*.png') # 所有图片绝对路径的列表
img_path = "/media/dell/2T/new/image1/"
# assert os.path.exists(img_path), "file: '{}' dose not exist.".format(img_path)
f_n = os.listdir(img_path) #遍历整个文件夹下的文件name并返回一个列表
# "a"表示以追加模式打开并写入到文件中, "w"表示如果文件存在则会清洗掉原文件的内容,然后把写的东西写进新文件,当前文件夹如果没有"XXX.txt"会自动创建
# f=open("/media/dell/2T/new/2.txt","w") # 写入txt
f=open("/media/dell/2T/new/2.csv","w") #写入csv
for line in f_n:
    f.write(line+'\n')
f.close()

你可能感兴趣的:(Python,python)