0

I have a users.csv file on the same folder as my python script. I use this to read through the folder:

users = []
with open(r"users.csv", encoding='UTF-8') as f: 

Is there a way to automatically read any .csv files within the directory without having to put "users.csv"?

Not sure how to word it but i'll give some context.

I have 10 folders, all folders have 1 users.csv file inside as well as a script that reads such file. Every time i have to switch the .csv file i have to rename it 10 times across all folders so the script reads it. Is there any way to automatically read the file if its in a csv format?

desertnaut
  • 57,590
  • 26
  • 140
  • 166
  • Have a look into directory recursion (`os.walk` for example) or the `glob` library. – S3DEV Jul 07 '21 at 19:16
  • Also [Find all files in a directory with extension .txt in Python](https://stackoverflow.com/q/3964681/6045800) – Tomerikoo Jul 07 '21 at 19:59

1 Answers1

0

You could do something like this:

import os
for file in os.listdir("."):
    if file.endswith(".csv"):
        #read it

To look in all sub-directories:

for root, dirs, _ in os.walk("."):
    for d in dirs:
        files = [os.path.join(root, d, f) for f in os.listdir(os.path.join(root, d)) if f.endswith(".csv")]
        if len(files)>0:
            for f in files:
                #read f
not_speshal
  • 22,093
  • 2
  • 15
  • 30