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

4
  • shot just need to append onto the filename for each loop Commented May 23, 2019 at 14:51
  • You can use df.to_csv('J:\Temp\'+filename+'_corrected.97o', index=False) Commented May 23, 2019 at 14:54
  • @Bugs404 jammer but your answer doesn't work Commented May 24, 2019 at 6:20
  • Possible duplicate of Rename multiple files in Python Commented May 24, 2019 at 15:31

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

3 Comments

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
this is what I get:
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"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.