5

我正在尝试解析文件夹中的所有文件并使用 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

4 回答 4

9
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])
于 2013-06-07T10:01:14.687 回答
5

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])
于 2013-06-07T10:02:09.790 回答
1
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
于 2017-09-18T14:36:49.583 回答
-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()
于 2021-04-25T13:45:46.057 回答