Advertisement
Guest User

Untitled

a guest
Oct 23rd, 2019
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.93 KB | None | 0 0
  1. import os
  2. import glob
  3. import csv
  4.  
  5. # import csv files from folder and change directory
  6. path = r'file_path'
  7. #os.chdir(path)
  8.  
  9. # create list of all files in directory
  10. allFiles = glob.glob(path + "/*.csv")
  11. print(allFiles)
  12.  
  13. # read in each file, add filename column
  14. with open('output.csv', 'w') as csvoutput:
  15. for i, fname in enumerate(allFiles):
  16. print(fname)
  17. with open(fname,'r') as csvinput:
  18. reader = csv.reader(csvinput)
  19. all = []
  20. if i == 0:
  21. row = next(reader)
  22. row.append('FileName')
  23. all.append(row)
  24. else:
  25. next(reader)
  26. writer = csv.writer(csvoutput, lineterminator='\n')
  27. print(os.path.basename(csvinput.name))
  28.  
  29. for row in reader:
  30. row.append(os.path.basename(csvinput.name))
  31. all.append(row)
  32. writer.writerows(all)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement