将文件夹中的文件名写入csv

时间:2013-06-07 09:58:11

标签: python csv

我正在尝试解析文件夹中的所有文件,并使用Python将文件名写入CSV。我使用的代码是

import os, csv

f=open("C:/Users/Amber/weights.csv",'r+')
w=csv.writer(f)
for path, dirs, files in os.walk("C:/Users/Amber/Creator"):
    for filename in files:
        w.writerow(filename)

我在CSV中获得的结果在一列中有单独的字母,而不是整个行名。如何解决?

4 个答案:

答案 0 :(得分:6)

import os, csv

f=open("C:/Users/Amber/weights.csv",'r+')
w=csv.writer(f)
for path, dirs, files in os.walk("C:/Users/Amber/Creator"):
    for filename in files:
        w.writerow([filename])

答案 1 :(得分:4)

writerow()需要一个序列参数:

import os, csv

with open("C:/Users/Amber/weights.csv", 'w') as f:
    writer = csv.writer(f)
    for path, dirs, files in os.walk("C:/Users/Amber/Creator"):
        for filename in files:
            writer.writerow([filename])

答案 2 :(得分:0)

import csv
import glob
with open('csvinput.csv', 'w') as f:
    writer = csv.writer(f)
    a = glob.glob('filepath/*.png')
    writer.writerows(zip(a)) #if you need the results in a column

答案 3 :(得分:-1)

import os

if __name__ == "__main__":

     datapath = open('output.csv", 'w')
     folderpath = 'C:\\Users\\kppra\\Desktop\\Data'

     for (root,dirs,files) in os.walk(folderpath,topdown=True):
          for f in files:
          datapath.write(f)
          datapath.write('\n')
datapath.close()