Swami Moksha
Swami Moksha

Reputation: 486

Writing filenames from folder in CSV in Python

I want to write the filenames of a particular folder in a CSV file( for the purpose of bulk uploading to the Internet Archive). The CSV must be written in the prescribed format.

I have tried the following code :

import os
import csv

path = '/media/sarada/Lectures & Ebooks/Ebooks/03-Bengali Books/18.Darshan'

with open('/home/sarada/ia_csv.csv', 'wb') as csvfile:
  writer = csv.writer(csvfile)
  writer.writerow(['identifier', 'file', 'description', 'subject[0]', 'title', 'creator', 'date', 'collection'])
  for dirpath, _, filenames in os.walk(path):
    if filenames:
      writer.writerow([os.path.basename(dirpath)] + filenames)

Now the file names are being printed in a row, i.e they are covering the description, title, creator etc. fields.

The issues:

Upvotes: 0

Views: 9530

Answers (2)

ahmad
ahmad

Reputation: 11

from PIL import Image
import csv
data=[]
with open('images.csv', 'w', newline='') as writeFile:
    writer = csv.writer(writeFile)
    for filename in os.listdir("ahmad"):
        data.append(filename)
        writer.writerow(data)
        data=[]
writeFile.close()

Upvotes: 1

zefixlluja
zefixlluja

Reputation: 468

For the simple CSV writer you will have to provide each field (you actually did this already for the header row). This is a bit tedious, you may want to consider using a DictWriter which is easier to handle/understand.

import os
import csv

path = 'YOUR_INPUT_DIRECTORY'

with open('YOUR_OUTPUT_FILE', 'wb') as csvfile:
  writer = csv.writer(csvfile)
  writer.writerow(['identifier', 'file', 'description', 'subject[0]', 'title', 'creator', 'date', 'collection'])
  for root, dirs, files in os.walk(path):
    for filename in files:
        writer.writerow(['', os.path.join(root,filename), '','','', 'opensource','',''])

Upvotes: 3

Related Questions