Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modifying a single line in a file

Is there a way, in Python, to modify a single line in a file without a for loop looping through all the lines?

The exact positions within the file that need to be modified are unknown.

like image 549
tew Avatar asked Jun 23 '11 16:06

tew


1 Answers

This should work -

f = open(r'full_path_to_your_file', 'r')    # pass an appropriate path of the required file
lines = f.readlines()
lines[n-1] = "your new text for this line"    # n is the line number you want to edit; subtract 1 as indexing of list starts from 0
f.close()   # close the file and reopen in write mode to enable writing to file; you can also open in append mode and use "seek", but you will have some unwanted old data if the new data is shorter in length.

f = open(r'full_path_to_your_file', 'w')
f.writelines(lines)
# do the remaining operations on the file
f.close()

However, this can be resource consuming (both time and memory) if your file size is too large, because the f.readlines() function loads the entire file, split into lines, in a list.
This will be just fine for small and medium sized files.

like image 123
Pushpak Dagade Avatar answered Nov 14 '22 21:11

Pushpak Dagade