Search code examples
pythonpandaslistdir

How to repeat the same operation for every file in a directory?


I have a folder with inside some .txt file. I would like to automatize the process in my code and repeat what I do for 'FALC_outp_assolute.txt' but for every file that is inside the same directory. The other files are called like ELET_outp_assolute.txt, BREN_outp_assolute.txt, ... so are different from the each other only by the initial four letters. This is my code, that works for one file:

df1 = pd.read_csv('FALC_outp_assolute.txt', sep='\s+', names=['Time', 'Data', 'H', 'N', 'E','X','Y','Z'], engine='python')

phi = df1.iloc[0,3].astype(float)
cos_phi = np.cos(phi)
sin_phi = np.sin(phi)

delta_est = ae + (c1e * cos_phi) + (s1e * sin_phi)

Somebody can help me!?


Solution

  • You can just run a for loop over all files in the directory:

    import os
    
    for f in os.listdir(path):
        df1 = pd.read_csv(os.path.join(path, f), sep='\s+', names=['Time', 'Data', 'H', 'N', 'E','X','Y','Z'], engine='python')
    
        phi = df1.iloc[0,3].astype(float)
        cos_phi = np.cos(phi)
        sin_phi = np.sin(phi)
    
        delta_est = ae + (c1e * cos_phi) + (s1e * sin_phi)