Reputation: 486
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?
Upvotes: 0
Views: 9530
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
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