Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

change first line of a file in python

Tags:

python

I only need to read the first line of a huge file and change it.

Is there a trick to only change the first line of a file and save it as another file using Python? All my code is done in Python and would help me to keep consistency.

The idea is to not have to read and then write the whole file.

like image 324
Dnaiel Avatar asked Feb 18 '13 23:02

Dnaiel


People also ask

How do you change a specific line in a text file in Python?

We will first open the file in read-only mode and read all the lines using readlines(), creating a list of lines storing it in a variable. We will make the necessary changes to a specific line and after that, we open the file in write-only mode and write the modified data using writelines().

How do you change a line in Python?

Newline character in Python: In Python, the new line character “\n” is used to create a new line. When inserted in a string all the characters after the character are added to a new line.


2 Answers

shutil.copyfileobj() should be much faster than running line-by-line. Note from the docs:

Note that if the current file position of the [from_file] object is not 0, only the contents from the current file position to the end of the file will be copied.

Thus:

from_file.readline() # and discard to_file.write(replacement_line) shutil.copyfileobj(from_file, to_file) 
like image 54
msw Avatar answered Sep 24 '22 01:09

msw


If you want to modify the top line of a file and save it under a new file name, it is not possible to simply modify the first line without iterating over the entire file. On the bright side, as long as you are not printing to the terminal, modifying the first line of a file is VERY, VERY fast even on vasy large files.

Assuming you are working with text-based files (not binary,) this should fit your needs and perform well enough for most applications.

import os newline = os.linesep # Defines the newline based on your OS.  source_fp = open('source-filename', 'r') target_fp = open('target-filename', 'w') first_row = True for row in source_fp:     if first_row:         row = 'the first row now says this.'         first_row = False     target_fp.write(row + newline) 
like image 45
Joshua Burns Avatar answered Sep 25 '22 01:09

Joshua Burns