Python - Open .txt files from a directory, apply a function to each dataframe, and export each .txt file into its own .xlsx file

Viewed 89

The number of columns and the name of columns vary between each file, but I always want to subtract the 3rd most-right column from the 2nd most-right column. From here, I want to call on files from a directory to be able to import multiple .txt files at once, then export each .txt file into its own .xlsx file with a unique name. For example, "Test.txt" would become "Test.xlsx" or "Test_Analyzed.xlsx", and "Test1.txt" would become "Test1.xlsx" or "Test1_Analyzed.xlsx"

import pandas as pd

df = pd.read_table(r'C:\Users\Me\Downloads\Time Trace(s).txt') 
df['Average - Background']  = df.iloc[ : , -2] - df.iloc[ : , -3]
df.to_excel('Test.xlsx', 'Sheet1')

I tried using this but I'm getting some errors.

import pandas as pd
import glob
import os

path = r'C:\Users\Me' 
all_files = glob.glob(path + "/*.txt")

for filename in all_files:
    df = pd.read_table(filename) 
    df['Average - Background']  = df.iloc[ : , -2] - df.iloc[ : , -3]
    newFilename = filename.replace('.xlsx', '_excel.xlsx')
    df.to_excel(newFilename, 'Sheet1')

I also tried using this instead to have more specificity in the files that are called on, but I also encountered some errors and wasn't sure if this worked for multiple files.

import pandas as pd
import glob
import os

os.chdir(r'C:\Users\Me')

df = ([pd.read_excel(file) for file in os.listdir() if file.startswith('VGlut_2022_2_16_10AP_10HZ')])
df['Average - Background']  = df.iloc[ : , -2] - df.iloc[ : , -3]
df.to_excel('C:\Users\Me')

Thanks!

0 Answers
Related