I'm looking for an approach where I can pass every single file from folder to open these files in binary mode

Question:

I have data in some files, and I want to check each file with my code. I was able to read a single file every time but I need to change the path every time in my code with the name of the respective file.

I have a folder where the all files are located. I want to open each file from that folder and pass it to the open in read bytes mode. How can I get files one after another?

readDataFromFile = open('abc.ecg', 'rb')
datatype = np.dtype('B')   #this is working as per expections

The above block is working as per expectations

for files in os.listdir('D:\ECGPROC\All Data\Normal'):
    print(files)

How can I pass these files to that readDataFromFile at one time?

Asked By: Tejas Badhe

||

Answers:

To read multiple files in a directory, you can use a for loop to iterate over the files in the directory and open each file with the open() function. Here is an example of how you can do that:

import os

# Path to the directory where the files are located
directory = 'D:\ECGPROC\All Data\Normal'

# Iterate over the files in the directory
for filename in os.listdir(directory):
    # Open the file in read binary mode
    readDataFromFile = open(os.path.join(directory, filename), 'rb')
    # Read the data from the file
    data = readDataFromFile.read()
    # Do something with the data
    # ...

In the above code, the os.path.join() function is used to construct the full path to the file, which is then passed to the open() function to open the file. You can then read the data from the file using the read() method of the file object.

Answered By: nklsw
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.