Search code examples
pythonfor-loopglob

accessing the same named files from directories


I have two directories that contain text files having same name. Though the file names are same they contain different data and I want to access same named files from both the directories at a time and wants to do some calculation. For testing purposes I have written below code but the loops does not access same named data file at a time....it choses random text files from both directories. Can anybody please suggest me how to access same named files by the below code?

nb: I have to access nearly 1000 files

import glob
data1=glob.glob('/home/liu/Music/datafiles1/*.txt')
data2=glob.glob('/home/liu/Music/datafiles2/*.txt')
for files in data:
    print(files)
    
    for file in data2:
        print(file)

Solution

  • You know the filenames in dir2 are the same as in dir1, so you don't need to list both directories. Just attach the filename you found to the second dir.

    from pathlib import Path
    
    dir1 = Path('/home/liu/Music/datafiles1')
    dir2 = Path('/home/liu/Music/datafiles2')
    
    for filepath1 in dir1.glob('*.txt'):
        filepath2 = dir2 / filepath1.name
        print(filepath1, filepath2)