Warm tip: This article is reproduced from stackoverflow.com, please click
python file-extension

Python save file with different extension

发布于 2020-03-27 15:42:41

I am aware of the os.path.splitext(file) function in Python, but this is changing the extenson of the existing file. I need to preserve the original file with its Extension as read file and create another file with another Extension as write file. For Example:

A = "File.inp"
pre, ext = os.path.splitext(A)
B = os.rename(A, pre + ".PRE")
with open("B" , 'w') as f1:
    with open("A",'r') as f2:
...

This command changes the Extension of the file form .inp to .PRE but without preserving the original file "File.inp". Any ideas or Solutions how can I preserve the original file with ist original Extension?

Questioner
GeMa
Viewed
18
Dmitry Shevchenko 2020-01-31 16:55

Here is an example:

base_file = "File.inp"
name, ext = base_file.split('.')
new_file = '{}.{}'.format(name, 'PRE')

with open(base_file , 'r') as f1:
    with open(new_file, 'w') as f2:
        f2.write(f1.read())