Reputation: 159
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?
Upvotes: 2
Views: 11787
Reputation: 320
I still do not have enough reputation to comment, so I'm adding an improvement to Dmitry's answer here.
He answered the question, but for other users learning from this thread, his answer will break (ValueError) if there are other dots in the file name.
rsplit(), which operates on the string in reverse order, with 1 as an argument, will split the string on the last occurrence of the delimiter.
base_file = "FileV0.1.2.inp"
name, ext = base_file.rsplit('.', 1)
new_file = '{}.{}'.format(name, 'PRE')
with open(base_file , 'r') as f1:
with open(new_file, 'w') as f2:
f2.write(f1.read())
Upvotes: 0
Reputation: 478
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())
Upvotes: 6
Reputation: 317
Sadly as soon as you use "os.rename()" or "os.replace()" it changes the original file and doesn't just "copy" it.
You could use shutil and this code:
import os
import shutil
A = "File.inp"
pre, ext = os.path.splitext(A)
B = pre + ".PRE"
shutil.copy(A,B)
with open(B , 'w') as f1:
with open(A,'r') as f2:
...
Upvotes: 1
Reputation: 274
not too clear. So you want to keep the original file and create a copy of it with a different extension?
I guess shutil.copy(origin, destination)
should work
Upvotes: 0