Skip to content

Instantly share code, notes, and snippets.

@leonardreidy
Created September 16, 2013 18:22
Show Gist options
  • Save leonardreidy/6584481 to your computer and use it in GitHub Desktop.
Save leonardreidy/6584481 to your computer and use it in GitHub Desktop.
Write a list of the contents of the current directory to a csv file in Python.
import glob
# glob does regular expression pattern matching, expansion etc, and, it returns
# a list of strings - nice and easy to work with
# List files starting with anything and ending with anything:
# glob.glob("*.*")
#
# to list only text files, for example, try:
# glob.glob("*.txt")
#
# or, for pdfs try:
# glob.glob("*.pdf")
# Store list of directories contents to a variable (globlet)
globlet = glob.glob("*.*")
# get the length of the variable for determining when to stop adding
# commas to our resulting comma-separated file
globletSize = len(globlet)
# open an appropriately named file for writing,
# and then use the csv module to create the output
# in said file!
#
# Note, if you want to have quotes around each element of the list
# use the following syntax:
# w = csv.writer(file, quoting=csv.QUOTE_ALL)
with open('outfile.txt', 'w') as file:
w = csv.writer(file, quoting=csv.QUOTE_NONE)
w.writerow(globlet)
@mrsof
Copy link

mrsof commented May 1, 2023

Import missing ?

import csv

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment