I am new to programming and am not sure of the best way to achieve my end goal.
I would like to create a script that will walk through a directory tree with hundreds of systematically named image files and then print the file names and file paths to a csv.
I understand how to use os.walk to list all images however I not sure how best to achieve my final output, eg should I create two lists (one with the file names and one with the file paths) or is there a better method for collecting my data for export to csv?
path = '/Users/User/Photos/'
for root, dirs, files in os.walk(path):
for x in files:
file_path= os.path.join(root, x)
print(file_path)
file_name= os.path.basename(x)
print(file_name)
Can somebody please point me towards the best method for printing the file_name and file_path pairs to a csv?
You can do it like so:
import os
path = '/Users/User/Photos/'
with open('tree.csv', 'w') as fout:
fout.write('file_name,file_path\n')
for root, dirs, files in os.walk(path):
for x in files:
file_path= os.path.join(root, x)
file_name= os.path.basename(x)
fout.write('{},{}\n'.format(file_name, file_path))
A csv file will be created under the name tree.csv
that looks like this:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.