1

I have a folder of 400 individual data files saved on my Mac with pathway Users/path/to/file/data. I am trying to write code that will iterate through each data file and plot the data inside of it, however I am having trouble actually importing this folder of all the data into python. Does anyone have a way for me to import this entire folder so I can just iterate through each file by writing

for file in folder:
   read data file 
   plot data file

Any help is greatly appreciated. Thank you!

EDIT: I am using Spyder for this also

Robert
  • 7,394
  • 40
  • 45
  • 64
  • 1
    Does this answer your question? [How to open every file in a folder?](https://stackoverflow.com/questions/18262293/how-to-open-every-file-in-a-folder) – Gino Mempin Nov 12 '20 at 22:55

1 Answers1

0

You can use the os module to list all files in a directory by path. os provides a function os.listdir(), that when a path is passed, lists all items located in that path, like this: ['file1.py', 'file2.py']. If no argument is passed, it defaults to the current one.

import os
path_to_files = "Users/path/to/file/data"

file_paths = os.listdir(path_to_files)

for file_path in file_paths:
    # reading file
    # "r" means that you open the file for *reading*
    with open(file_path, "r") as file:
        lines = file.readlines()
        # plot data....
lionrocker221
  • 171
  • 3
  • 8