user3848207
user3848207

Reputation: 4917

Replace only first line of text file in python

I have a text file which consists of many lines of text.

I would like to replace only the first line of a text file using python v3.6 regardless of the contents. I do not need to do a line-by-line search and replace the line accordingly. No duplication with question Search and replace a line in a file in Python

Here is my code;

import fileinput

file = open("test.txt", "r+")
file.seek(0)
file.write("My first line")

file.close()

The code works partially. If the original first line has string longer than "My first line", the excess sub-string still remains. To be clearer, if original line is "XXXXXXXXXXXXXXXXXXXXXXXXX", then the output will be "My first lineXXXXXXXXXXXXXX". I want the output to be only "My first line". Is there a better way to implement the code?

Upvotes: 6

Views: 25147

Answers (3)

Marquinho Peli
Marquinho Peli

Reputation: 5139

If your file is a big xml, rewriting the whole file is not doable. In this case blank spaces won't matter, then you can replace the extra characters by white spaces. Example removing the namespace from xml file:

with open(r'C:\Users\MyUser\Desktop\catalog.xml', 'r+') as f:
    l1 = f.readline()
    l2 = f.readline()
    replacing = r'xmlns="http://www.namespace1.com/xml/catalog/" '
    newL2 = l2.replace(replacing, '').rstrip()
    f.seek(len(l1))
    f.write(newL2)
    f.write(' ' * len(replacing))

Upvotes: 2

bhansa
bhansa

Reputation: 7504

Reading and writing content to the file is already answered by @Zhang.

I am just giving the answer for efficiency instead of reading all the lines.

Use: shutil.copyfileobj

from_file.readline() # and discard
to_file.write(replacement_line)
shutil.copyfileobj(from_file, to_file)

Reference

Upvotes: 8

Yilun Zhang
Yilun Zhang

Reputation: 9018

You can use the readlines and writelines to do this. For example, I created a file called "test.txt" that contains two lines (in Out[3]). After opening the file, I can use f.readlines() to get all lines in a list of string format. Then, the only thing I need to do is to replace the first element of the string to whatever I want, and then write back.

with open("test.txt") as f:
    lines = f.readlines()

lines # ['This is the first line.\n', 'This is the second line.\n']

lines[0] = "This is the line that's replaced.\n"

lines # ["This is the line that's replaced.\n", 'This is the second line.\n']

with open("test.txt", "w") as f:
    f.writelines(lines)

Upvotes: 9

Related Questions