Writing filenames from a folder into a csv

2020-07-17 16:15发布

问题:

I'm trying to parse all files in a folder and write the filenames in a CSV using Python. The code I used is

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)

The result I'm getting in the CSV has individual alphabets in one column rather than the entire row name. How to fix that?

回答1:

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])


回答2:

writerow() expects a sequence argument:

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])


回答3:

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


标签: python csv