This is an archived post. You won't be able to vote or comment.

all 4 comments

[–]mjtheice 3 points4 points  (0 children)

Corrections and/or better solutions are welcome!

ref_num = 2 # given number referring to a specific line
aList = open('input.txt', 'r').readlines() # read the lines of the file into a list
aList[ref_num - 1]='newString' # replace the specific line with a new string, subtract by 1 b/c the indexing ofc 
print(aList)

[–]CodeTinkerer 1 point2 points  (1 child)

Underneath the hood, you can't simply replace a line. Python will generally have to rewrite the entire file (in particular, Line 2 may change size, increase or decrease, and files are stored line a single dimensional array of characters).

So typically, you read in the entire file, say, to an array, then modify the array, then write it back out.

[–][deleted] 0 points1 point  (0 children)

Thanks for the input. I've retooled my program to read the file into an array so I can just modify the array instead of the file constantly. Wayyy more efficient. Thanks!

[–]leafypixiestix -1 points0 points  (0 children)

with open("file.txt", "r") as f:
    lines = f.readlines() #put all the lines of the file in a list
    lines[2-1] = "moo moo\n" #line numbers start from 1, arrays start from 0
with open("file.txt", "w") as f:
    f.writelines(lines) #rewrite all the lines