我正在使用熊猫读取多个文件,并且需要使用原始的filename_corrected保存每个文件。如何使用原始文件名+前缀或数字来重命名输出文件?
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)
输出文件应名为:filename_corrected.97o
答案 0 :(得分:1)
您可以使用基于旧名称的格式字符串来创建新文件名:
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)