Ad

Read Two Files From Two Paths At Within Same Loop_python

- 1 answer

I have two paths each path contains many files, each file contains data for one day. I need to read the file from the first path, and the other file from the other path that corresponds to the same day. [in the same python loop I want to read the file of the first day in each path]. The files are with the same name and sequence in each path. I'm trying to use os.listdir(path) in for loop instead of with open (file) as file because I want to read the file as a data frame using pandas. Then use pandas to do data aggregation for each file.

Ad

Answer

I assume, you are sure, that a file always exists in both directories.

Is this what you are asking?

path1 = "path1"
path2 = "path2"
for fname in os.listdir(path1):
    fname1 = os.path.join(path1, fname)
    fname2 = os.path.join(path2, fname)
        # do your processing here

If it can happen, that a file exists in path1 but not in path 2 you have to check with os.path.isfile() the presence of the other file before opening and skip if absent

Ad
source: stackoverflow.com
Ad