Reputation:
I have created a program that picks up names of all files in a directory using python glob package
import glob
path = 'D:\Movies\American and Brit Cinema'
files = [f for f in glob.glob(path + "**/*.avi", recursive=True)]
for f in files:
print(f[35:])
I do get my desired output:
The.Descendants.2011.
The.Expendables.2010.
The.Hangover.2009
The.Impossible.2012
the.invention.of.lying.2009
The.Muppets.2011.
The.Social.Network.2010
Tron.Legacy.2010
However, I want to take this list of movie titles and export it to a csv
When I try I get the below error-
f.to_csv('EnglishMovies.docx')
AttributeError: 'str' object has no attribute 'to_csv'
I tried converting to a list as well but I just get messy data. I just want my final csv file to have the names of all the files in my directory
Upvotes: 0
Views: 974
Reputation: 31
If you want to use the .to_csv
method, you can create a data frame and then write it to csv.
import glob
import pandas as pd
path = 'D:\Movies\American and Brit Cinema'
files = [f for f in glob.glob(path + "**/*.avi", recursive=True)]
df = pd.DataFrame(columns = ['Movie Names'])
df['Movie Names'] = files
df['Movie Names'] = df['Movie Names'].str[35:]
df.to_csv(path + '\EnglishMovies.csv')
Upvotes: 0
Reputation: 1115
You can open the .csv
file directly and write to it.
with open("path_to_csv/movies.csv", "w") as fp:
for f in files:
fp.write(f+"\n")
Upvotes: 0
Reputation: 4021
Use csv
module
import csv
with open('output.csv', mode='w') as csvfile:
writer = csv.writer(csvfile, delimiter=',', quoting=csv.QUOTE_MINIMAL)
for f in files:
writer.writerow([f])
Upvotes: 2