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?

user3848207
  • 3,737
  • 17
  • 59
  • 104
  • Possible duplicate of [Search and replace a line in a file in Python](https://stackoverflow.com/questions/39086/search-and-replace-a-line-in-a-file-in-python) – wwii Sep 28 '17 at 14:40
  • Welcome to SO. Please take the time to read [ask] and the links it contains. – wwii Sep 28 '17 at 14:41
  • 1
    @wwii , I don't think there is a duplication. I have edited the question. – user3848207 Sep 28 '17 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.`. – wwii Sep 28 '17 at 14:53

2 Answers2

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)
TYZ
  • 8,466
  • 5
  • 29
  • 60
  • Please do not post images of code or data. Please take the time to read [ask] and the links it contains. – wwii Sep 28 '17 at 14:26
  • Is good practice to open a file second time without having formally closed it the first? – saintsfan342000 Sep 28 '17 at 14:27
  • @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. – TYZ Sep 28 '17 at 14:29
  • 2
    It is better practice to open a file using a context manager - `with open(...) as f:...` – wwii Sep 28 '17 at 14:31
  • 1
    @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. – user3848207 Sep 28 '17 at 14:56
  • `with open("test.txt", "w") as f: f.writelines(lines)` isnt this unecessarily writing unchanged lines from line2 again? – Yugandhar Chaudhari Nov 13 '19 at 09:39
  • When I do the above, it throws an error saying `lines` needs to be a string and it found a list? – Patrick_Chong Apr 05 '23 at 09:46
7

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

bhansa
  • 7,282
  • 3
  • 30
  • 55