-1

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!?

Helena
  • 7
  • 6
  • 1
    Use a loop! To get files from the current directory, module ``os`` has a ``os.listdir`` function. You can then filter those files based on their name (except the four first characters), e.g., with ``filename[4:] == _outp_assolute.txt``. – Guybrush Mar 28 '19 at 13:54
  • 4
    just iterate over file `flist = [f for f in os.listdir() if f.endswith('outp_assolute.txt')]` – Rocky Li Mar 28 '19 at 13:54
  • @RockyLi Clean approach - you should write that as an answer ;) – iLuvLogix Mar 28 '19 at 13:55
  • possible duplicate of https://stackoverflow.com/questions/20906474/import-multiple-csv-files-into-pandas-and-concatenate-into-one-dataframe ? – yuvgin Mar 28 '19 at 13:56

1 Answers1

0

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) 
shayelk
  • 1,606
  • 1
  • 14
  • 32