MichaelP
MichaelP

Reputation: 41

How to save os.listdir output as list

I am trying to save all entries of os.listdir("./oldcsv") separately in a list but I don't know how to manipulate the output before it is processed.

What I am trying to do is generate a list containing the absolute pathnames of all *.csv files in a folder, which can later be used to easily manipulate those files' contents. I don't want to put lots of hardcoded pathnames in the script, as it is annoying and hard to read.

import os

for file in os.listdir("./oldcsv"):
    if file.endswith(".csv"):
        print(os.path.join("/oldcsv", file))

Normally I would use a loop with .append but in this case I cannot do so, since os.listdir just seems to create a "blob" of content. Probably there is an easy solution out there, but my brain won't think of it.

Upvotes: 0

Views: 1392

Answers (1)

tidylobster
tidylobster

Reputation: 723

There's a glob module in the standard library that can solve your problem with a single function call:

import glob 

csv_files = glob.glob("./*.csv")  # get all .csv files from the working dir
assert isinstance(csv_files, list)

Upvotes: 1

Related Questions