I am trying to write a python script that will take in a user specified directory and then write the contents of that directory to a csv file. The challenge I am facing is to write the folder structure to the csv in a certain format. The format I need is shown below:
I've tried using os.walk(dir) to list the directories and files but I'm having trouble writing to the csv in the above format.
I've also found some code that creates a nested dictionary out of a given folder structure but I'm finding it very difficult to navigate through this nested structure and write the rows in the way that I need.
If anyone has an easier approach to accomplishing this task it would be much appreciated.
Ok, here is the code that does the job:
import os
import csv
data = []
for root, dirs, files in os.walk('.'):
for f in files:
l = root.split('/') + [f]
data.append(l)
with open('output.csv', 'wb') as f:
writer = csv.writer(f)
for d in data:
writer.writerow(d)
If you're on windows, replace split('/')
with split('\\\\')
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.