Export Glob list to CSV

Viewed 33

I have a folder named "Photos" that contains several images. I am using Glob to list all these images along with their full directory paths. I can print the list and see the full list of paths, however, I am now struggling to export this list into a CSV with a single column. My code is as follows:

Import glob

for file in glob.glob(r"C:\Users\myself\Photos*"):
    print(file)

Normally I would use Pandas to read CSVs by putting them into a dataframe, but for a glob list I am struggling

appreciate any guidance or help

1 Answers

You're close. Use this :

import glob
import pandas as pd

list_of_pictures = []
for file in glob.glob(r"C:\Users\myself\Photos\*"):
    list_of_pictures.append(file)
    
pd.DataFrame(list_of_pictures).to_csv(r'path&name_of_your_csvfile.csv', index=False, header=None)

Or with pathlib :

from pathlib import Path
import pandas as pd

list_of_pictures=[]
for file in Path(r'C:\Users\myself\Photos').glob('**/*'):
    list_of_pictures.append(str(file.absolute()))
    
pd.DataFrame(list_of_pictures).to_csv(r'path&name_of_your_csvfile.csv', index=False, header=None)
Related