Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing filenames from a folder into a csv

Tags:

python

csv

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?

like image 878
m_amber Avatar asked Jun 07 '13 09:06

m_amber


People also ask

How do I export a list of files from a folder to text?

Right-click that folder and select Show more options. Click Copy File List to Clipboard on the classic menu. You'll still need to paste the copied list into a text file.


2 Answers

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])
like image 131
falsetru Avatar answered Oct 01 '22 07:10

falsetru


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])
like image 31
alecxe Avatar answered Oct 01 '22 07:10

alecxe