Home > Software engineering >  open a folder to then use the files in python correctly
open a folder to then use the files in python correctly

Time:01-25

Usually I navigate to the folder I am extracting data from using a terminal, as below.

df2=pd.read_csv('10_90_bnOH-MEA.csv',usecols=[1])

If I have multiple files and want to do the above for these, how do I specify the folder to open and then name the file correctly?

Without naming "C:\Users\X\Desktop\Y\Z\10_90_bnOH-MEA.csv"

naming "C:\Users\X\Desktop\Y\Z\10_90_bnOH-MEA.csv"

CodePudding user response:

You want listdir from the os module.

import os

path = "C:\\Users\\X\\Desktop\\Y\\Z\\"
files = os.listdir(path)
print(files)

dataframe_list = []
for filename in files:
    dataframe_list.append(pd.read_csv(os.path.join(path,filename)))

CodePudding user response:

You should open the desired directory and loop through all the files then do something to them.

# import required module
import os
# assign directory
directory = 'files'
 
# iterate over files in
def goThroughDirectory(directory):
    for filename in os.listdir(directory):
        f = os.path.join(directory, filename)
        # checking if it is a file
        if os.path.isfile(f):
            # do something

If you also want to loop through all the files in a directory you should add a check for if os.path.isdir(f) like this

...

def goThroughDirectory(directory):
    for filename in os.listdir(directory):
        f = os.path.join(directory, filename)
        # checking if it is a file
        if os.path.isfile(f):
            # do something
        elif os.path.isdir(f):
            # its not a file but a directory then loop through that directory aswell
            goThroughDirectory(directory   "\"   f)

for more information you should check geeksforgeeks

  • Related