Python Forum
Delete all contents of a file from the fifth line? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Delete all contents of a file from the fifth line? (/thread-25998.html)



Delete all contents of a file from the fifth line? - PythonNPC - Apr-18-2020

Hello,

I want to delete all the contents of the file from under the fifth line.

Is this doable?
I don't want to just print the file on the console, I actually want the contents of the file to be deleted from the fifth line and then to be saved.

I tried searching on the internet but was not able to find anything, maybe I just suck search at searching.

Can anyone help?
Thank you.


RE: Delete all contents of a file from the fifth line? - buran - Apr-18-2020

just read the file up to 5th row and save it as temp file, after that replace the original.

or as an alternative is using fileinput with inplace=True
import fileinput

with fileinput.input(files=('sample.dat',), inplace=True) as f:
    for _ in range(5):
        print(next(f), end='') # this will write to original file
Quote:Optional in-place filtering: if the keyword argument inplace=True is passed to fileinput.input() or to the FileInput constructor, the file is moved to a backup file and standard output is directed to the input file (if a file of the same name as the backup file already exists, it will be replaced silently). This makes it possible to write a filter that rewrites its input file in place. If the backup parameter is given (typically as backup='.<some extension>'), it specifies the extension for the backup file, and the backup file remains around; by default, the extension is '.bak' and it is deleted when the output file is closed. In-place filtering is disabled when standard input is read.