0

I wrote a code that starts with

import pandas as pd
# Code starts by reading one txt file
df=pd.read_fwf(r'C:\Users\youngrakchoi\Desktop\.filename.txt',sep='')

#-------My code--------#

# Code ends with saving the results
VOLTAGE_fin.to_excel(r'C:\Users\youngrakchoi\Desktop\NAME.xlsx')

Now I would like to run this code to all files saved in specific directory(folder) and save the file as the original file name (eg. save VOLTAGE_fin as 'filename').

Could anybody help me to solve this issue?

min chul
  • 17
  • 2
  • 1
    list the files from the folder using glob and iterate over them https://stackoverflow.com/questions/10377998/how-can-i-iterate-over-files-in-a-given-directory –  Aug 16 '22 at 15:04
  • Your question is slightly *unclear*. Are you asking how to use the variable name as the name of file being saved? If that's the case, you can use string formatting. – vyi Aug 16 '22 at 15:04
  • @vyi I am trying to apply my coding to multiple files in one folder and at the end I would like to save my results into a original file name(say if I call 1.txt 2.txt ... and my results should be saved as 1.xlsx 2.xlsx ...) – min chul Aug 16 '22 at 16:20

2 Answers2

0

I think it will do the job.

my_var_name = [ k for k,v in locals().items() if v == VOLTAGE_fin][0]
VOLTAGE_fin.to_excel(f"C:\\Users\\youngrakchoi\\Desktop\\{my_var_name}.xlsx")
0

I am trying to apply my coding to multiple files in one folder

You can read the files (their names) in a given directory with the listdir function from os module. A minimal example follows:

import os
path = 'C:\\Users\\youngrakchoi\\Desktop\\my_dir\\'
all_files = os.listdir(path)
for file_name in all_files:
    ## Do your work 
    ## Finally save your output in xlsx format as follows
    pd.to_excel("{}/{}.xlsx".format(path, file_name))
vyi
  • 1,078
  • 1
  • 19
  • 46