Search code examples
pythonstringcsvglob

How do I convert a dataframe of strings to csv in python?


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


Solution

  • 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])