I'm trying to make a script work under windows, but seem to run in circles. It works on posix filesystems. In the code below, i'm using the library tempfile in a with statement to create a tempfile and copy the source into it. Then i want to use the function strip_whitespaces_from_file() on this tempfile. But instead the permission error below.
import tempfile
import shutil
import fileinput
source_file_name = r"C:\Users\morph\Stuff\test.txt"
def strip_whitespaces_from_file(input_file_path: str):
with fileinput.FileInput(files=(input_file_path,), inplace=True) as fp:
for line in fp:
print(line.strip())
with tempfile.NamedTemporaryFile(delete=False) as dest_file:
shutil.copy(source_file_name, dest_file.name)
strip_whitespaces_from_file(dest_file.name)
Instead i get this output:
"PermissionError: [WinError 32] The process cannot access the file because it is being used by another process:
'C:\\Users\\morph\\AppData\\Local\\Temp\\tmpbvywadw7' -> 'C:\\Users\\morph\\AppData\\Local\\Temp\\tmpbvywadw7.bak'
The error message seems quite straightforward, but i can't find a way around it. There are a couple of answers, e.g. this one, but that would mean i have to close the file before i work on it. Apparently the tempfile is opened by the same process that wants to write to it? Isn't that the whole point? I'm confused.
Edit: Below is my clunky workaround. But it illustrates the need for delete=False
. If i remove it i get a FileNotFoundError
. To me that looks like the file i removed immediately after creating it in the first line of below code. The manual closing and os.unlink also shouldn't be needed.
with tempfile.NamedTemporaryFile(delete=False) as temp:
with open(source_file_name, 'r') as src_file:
for line in src_file:
stripped_line = line.strip()+"\n"
temp.write(stripped_line.encode('utf-8'))
src_file.close()
temp.close()
# here would be an external converter using the temp file as argument
os.unlink(temp.name)
print(os.path.exists(temp.name))