0

I have looked over the similar questions, and not found a solution to my problem.

I am trying to insert a line of text onto the second line of a text file, however I don't want to open and close the text file as I am running this code over a large number of files, and don't want to slow it down. I found this answer to a similar question, and have been working through it; where I use tempfile to create a temporary file which is working perfectly: as reproduced below:

from pathlib import Path
from shutil import copyfile
from tempfile import NamedTemporaryFile

sourcefile = Path("Path\to\source").resolve()
insert_lineno = 2
insert_data = "# Mean magnitude = " + str(mean_mag)+"\n"
with sourcefile.open(mode="r") as source:
    destination = NamedTemporaryFile(mode="w", dir=str(sourcefile.parent))
    lineno = 1

    while lineno < insert_lineno:
        destination.file.write(source.readline())
        lineno += 1
    
    destination.file.write(insert_data)
    
    while True:
        data = source.read(1024)
        if not data:
            break
        destination.file.write(data)
    
# Finish writing data.
destination.flush()
# Overwrite the original file's contents with that of the temporary file.
# This uses a memory-optimised copy operation starting from Python 3.8.
copyfile(destination.name, str(sourcefile))
# Delete the temporary file.
destination.close()

The second to last command, copyfile(destination.name, str(sourcefile)) is not working, and I am getting

[Errno 13] Permission Denied: 'D:\My_folder\Subfolder\tmp_s570_5w'

I think perhaps the problem is I can't copy from the temporary file because it is currently open, but if I close the temporary file it gets deleted, so I can't close it before copying either.

EDIT: When I run my code on Linux I don't get any errors, so it must be some kind of Windows permission problem?

1 Answers1

1

Try this:

sourcefile = Path("Path\to\source").resolve()
    insert_lineno = 2
    insert_data = "# Mean magnitude = " + str(mean_mag)+"\n"
    with sourcefile.open(mode="r") as source:
        with NamedTemporaryFile(mode="w", dir=str(sourcefile.parent)) as destination:
            lineno = 1

            while lineno < insert_lineno:
                destination.file.write(source.readline())
                lineno += 1
            
            destination.file.write(insert_data)
            
            while True:
                data = source.read(1024)
                if not data:
                    break
                destination.file.write(data)
        
            # Finish writing data.
            destination.flush()
            # Overwrite the original file's contents with that of the temporary file.
            # This uses a memory-optimised copy operation starting from Python 3.8.
            copyfile(destination.name, str(sourcefile))
            # Delete the temporary file.
            destination.close()
Roni Antonio
  • 1,334
  • 1
  • 6
  • 11