0

I'm still pretty new to python and trying my best to teach myself. What I'm trying to do is get 3 different file paths written to a csv after iterating through a folder. I'm having an issue in that only the first file path that should print is printing. I'm hoping to get the following output printed to a csv:

['C:\\Users\\micha\\Documents\\USGS-NHD DATA\\NHDwaterbody.shp']
['C:\\Users\\micha\\Documents\\USGS-NHD DATA\\VietnamPA_name__Tam Dao.shp']
['C:\\Users\\micha\\Documents\\USGS-NHD DATA\\WBD_11.shp']

But I end up only getting one this as my output:

C:\Users\micha\Documents\USGS-NHD DATA\VietnamPA_name__Tam Dao.shp

This is the code I've come up with currently. I'd appreciate any input as to how I could get all three items to print to a csv instead of just the one.

import os
import csv
# assign directory
directory = 'C:\\Users\\micha\\Documents\\USGS-NHD DATA'
 
# iterate over files in
# that directory
for filename in os.listdir(directory):
    f = os.path.join(directory, filename)
    # checking if it is a file shp
    if f.endswith('.shp'):
        data= [f]
        n = open('C:\\Users\\micha\\Documents\\create.csv','w')
        writer = csv.writer(n)
        for item in data:
            writer.writerows([data])
  • What if you open the file and create your writer before entering the `for` cycle? – Dmitry Grekov Aug 13 '21 at 07:07
  • When I do that I only get 1 file as my output again but this time it was slightly different, this is what I got instead: C:\Users\micha\Documents\USGS-NHD DATA\WBD_11.shp. thank you for the suggestion though! – mercurial_app Aug 13 '21 at 07:13
  • Use write mode `'a'` for appending. https://docs.python.org/3/library/functions.html#open - `'w'` : open for writing, truncating the file first – AcK Aug 13 '21 at 07:16

1 Answers1

0

Create the csv file before the loop. if you do it inside the loop, it will be overwritten for each file in the directory:

with open('C:\\Users\\micha\\Documents\\create.csv','w') as n:
    writer = csv.writer(n)
    for filename in os.listdir(directory):
        f = os.path.join(directory, filename)
        # checking if it is a file shp
        if f.endswith('.shp'):
            writer.writerow([f])
napuzba
  • 6,033
  • 3
  • 21
  • 32