6

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?

4
  • Possible duplicate of Search and replace a line in a file in Python Commented Sep 28, 2017 at 14:40
  • Welcome to SO. Please take the time to read How to Ask and the links it contains. Commented Sep 28, 2017 at 14:41
  • 1
    @wwii , I don't think there is a duplication. I have edited the question. Commented Sep 28, 2017 at 14:50
  • 1
    The basic operation of replacing content in the file is the same: If you read the plethora of answers to that question you will find a solution, possibly from a combination of answers. Your problem can be rephrased as search for the first line in a file and replace it.. Commented Sep 28, 2017 at 14:53

3 Answers 3

9

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)
Sign up to request clarification or add additional context in comments.

7 Comments

Please do not post images of code or data. Please take the time to read How to Ask and the links it contains.
Is good practice to open a file second time without having formally closed it the first?
@saintsfan342000 Actually that's a good point. I was just trying to show the solution for the question that's asked. You should always close the file and then reopen it.
It is better practice to open a file using a context manager - with open(...) as f:...
@Zhang Yilun, Thanks. Your code works. However, I was wondering if there can be a more efficient way to do so. Your code reads all the lines and writes back all the lines of the text file. However, only the first line needs to be read and written.
|
8

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

Comments

2

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))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.