0

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:

  • File names should be printed in the file column only.

  • How to print only the file name(stripping the extension portion) in title column?

  • How to add a string(e.g opensource) in
    writer.writerow([os.path.basename(dirpath)] + filenames) so that
    the creator column contains that string?

2 Answers 2

3

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','',''])
Sign up to request clarification or add additional context in comments.

Comments

1
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()

1 Comment

Welcome to StackOverflow! Please edit your answer to include an explanation of your solution. This will make your answer more useful, and make it more likely for it to be upvoted :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.