简体   繁体   English

将带有扩展名的文件名保存到现有文件名

[英]saving a filename with an extension to an existing filename

I would like to save a file by adding an extension to the existing filename, by extension I do not mean change.csv to.HTML.我想通过在现有文件名中添加扩展名来保存文件,扩展名并不是指将.csv 更改为.HTML。 What I mean is if I have an existing file file1.csv I would like to save the other file as file1_processed.csv.我的意思是,如果我有一个现有文件 file1.csv,我想将另一个文件另存为 file1_processed.csv。

I tried doing this我试着这样做

data = pd.read_csv("file1.csv")
df = x
df.to_csv(os.path.basename(data) + '_' + 'processed' + '.csv')

however, it gives an error但是,它给出了一个错误

TypeError: expected str, bytes or os.PathLike object, not DataFrame类型错误:预期 str、字节或 os.PathLike object,而不是 DataFrame

filename = "file1"
data = pd.read_csv(filename + ".csv")
# ...
df.to_csv(filename + '_processed.csv')

data has contents of file file1.csv , not the file name. data具有文件file1.csv的内容,而不是文件名。 You need to assign the file name to a variable if the name of the file is not same always.如果文件名始终不同,则需要将文件名分配给变量。

file_name = "file1.csv"
data = pd.read_csv(file_name )
df = x
name, extension = os.path.splitext(os.path.basename(file_name))
df.to_csv(name + '_' + 'processed' + extension)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM