[英]Printing file name and file path to a csv
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.我想创建一个脚本,它将遍历包含数百个系统命名的图像文件的目录树,然后将文件名和文件路径打印到 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?我了解如何使用 os.walk 列出所有图像但是我不确定如何最好地实现我的最终 output,例如我应该创建两个列表(一个带有文件名,一个带有文件路径)还是有更好的方法收集我的数据以导出到 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?有人可以指出将文件名和文件路径对打印到 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:将在名称
tree.csv
下创建一个 csv 文件,如下所示:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.