Writing to CSV Files in Python

Goal: Writing all files' names in any folder to a CSV File in Python


  • Working Python Shell like IDLE
  • Notepad ++ or any other text editor

Lets begin

1. Open Python Shell "IDLE" and save a file named "Allfiles.py"

2. Copy below code to "Allfiles.py"

import os
import csv
with open('fileslist.csv', mode='w') as new_file:
        wri = csv.writer(new_file)
        for i in range(len(file)):
            wri1 = file[i]

3. Save and press F5 to execute.

4. Open folder 'data' in C: drive and you will find a file named 'fileslist.csv'.

5. Open fileslist.csv in NotePad++.

6. You will see one empty line after each file name. To delete empty row, select edit-->Line Operations-->Remove Empty Lines

7. To remove unwanted commas, do CTRL-F, Click Replace, Put "," in Find and click Replace All.

8. That's it. You have a list of files in your desired folder.