Home > Mobile >  How do i use file path list in the loop?
How do i use file path list in the loop?

Time:08-30

First of all, I have to say that I'm totally new to Python. I am trying to use it to analyze EEG data with a toolbox. I have 30 EEG data files.

I want to create a loop instead of doing each analysis separately. Below you can see the code I wrote to access all the directories to be analyzed in a folder:

import os
path = 'my/data/directory'
folder = os.fsencode(path)

filenames = []

for file in os.list(folder):
    filename = os.fsdecode(file)
    if filename.endswith('.csv') and filename.startswith('p'): # whatever file types you're using
        filenames.append(filename)
filenames.sort()

But after that, I couldn't figure out how to use them in a loop. This way I could list all the files but I couldn't find how to refer each of them in iteration within the following code:

file = pd.read_csv("filename", header=None)
fg.fit(freqs, file, [0, 60]) #The rest of the code is like this, but this part is not related

Normally I have to write the whole file path in the part that says "filename". I can open all file paths with the code I created above, but I don't know how to use them in this code respectively.

I would be glad if you help.

CodePudding user response:

first of all, this was a good attempt.

What you need to do is make a list of files. From there you can do whatever you want...

You can do this as follows:

from os import listdir
from os.path import isfile, join

mypath = 'F:/code'  # whatever path you want
onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))]

# now do the for loop
for  i in onlyfiles:
    # do whatever you want
    print(i)


  • Related