2

I am reading multiple files using pandas and need to save each file with the original filename_corrected. How do you rename the output file with it's original filename + a prefix or number?

import pandas as pd
import glob
import os

#Read all files in using pandas
path = r'J:\Temp\\' 
all_files = glob.glob(path + "/*.97o")

for filename in all_files:
   df = pd.read_csv (filename)
   df = df.replace(to_replace ='1997     7    23 ', value = '2019     5    23 ', regex = True)
   df = df.replace(to_replace ='97  7 23', value = '19  5 23', regex = True)
   df.to_csv('J:\Temp\94512040_corrected.97o', index=False)

Output file should be called: filename_corrected.97o

cs95
  • 379,657
  • 97
  • 704
  • 746
M.Lord
  • 101
  • 10

1 Answers1

2

You can create a new filename using a format string based on the old name:

import pandas as pd
import glob
import os

#Read all files in using pandas
path = r'J:\Temp\\' 
all_files = glob.glob(path + "/*.97o")

for filename in all_files:

   df = pd.read_csv(filename)
   df = df.replace(to_replace ='1997     7    23 ', value = '2019     5    23 ', regex = True)
   df = df.replace(to_replace ='97  7 23', value = '19  5 23', regex = True)
   fileBaseName = os.path.basename(filename).split('.')[0]
   newFilename = '{}{}_corrected.97o'.format(path, fileBaseName)
   df.to_csv(newFilename, index=False)
kudeh
  • 883
  • 1
  • 5
  • 16
  • Hi thanks for the answer but seems to be messing with the path - getting a 'no such file or directory' error - code seems to be adding extra \\ into the filepath – M.Lord May 24 '19 at 07:42
  • this is what I get: – M.Lord May 24 '19 at 08:01
  • FileNotFoundError: [Errno 2] No such file or directory: "J:\\Temp\\Michael\\Python\\Rinex Date Error\\J:\\Temp\\Michael\\Python\\Rinex Date Error\\'+filename+_corrected.97o_corrected.97o" – M.Lord May 24 '19 at 08:01