Refresh lines in a text file at a specific location

I would like to find the best solution to achieve the following three steps:

  • reading lines in a given line
  • update lines
  • write updated lines back

Below is my code that works, but I wonder if there are better (simple) solutions?

new='99999'

f=open('C:/Users/th/Dropbox/com/MS1Ctt-P-temp.INP','r+')
lines=f.readlines()
#the row number we want to update is given, so just load the content
x = lines[95]
print(x)
f.close()


#replace
f1=open('C:/Users/th/Dropbox/com/MS1Ctt-P-temp.INP')
con = f1.read()
print con
con1 = con.replace(x[2:8],new) #only certain columns in this row needs to be updated
print con1
f1.close()


#write
f2 = open('C:/Users/th/Dropbox/com/MS1Ctt-P-temp.INP', 'w')
f2.write(con1)
f2.close()

Thank! UPDATE: getting an idea from jtmoulia this time gets easier

def replace_line(file_name, line_num, col_s, col_e, text):
    lines = open(file_name, 'r').readlines()
    temp=lines[line_num]
    temp = temp.replace(temp[col_s:col_e],text)
    lines[line_num]=temp
    out = open(file_name, 'w')
    out.writelines(lines)
    out.close()
+3
source share
4 answers

Well, for starters, you don’t need to constantly open and read from a file. The mode r+allows you to read and write to this file.

Maybe something like

with open('C:/Users/th/Dropbox/com/MS1Ctt-P-temp.INP', 'r+') as f:
    lines = f.readlines()
    #... Perform whatever replacement you'd like on lines
    f.seek(0)
    f.writelines(lines)

Also, editing a specific line in a text file in python

+1
source

, , , . , , (, ) .

, , , , , standard mmap . .

.

+3

- ( Webmin), PERL, , Webmin, . ( ), Python. ( PERL , , "slurp" ). ( , , ( ). , .) split . (, 0). , " " . , ( ). , join, . .

, PERL, , :

our @filelines = ();
our $lineno = 43;
our $oldstring = 'foobar';
our $newstring = 'fee fie fo fum';
$filelines[$lineno-1] =~ s/$oldstring/$newstring/ig; 
# "ig" modifiers for case-insensitivity and possible multiple occurences in the line
# use different modifiers at the end of the s/// construct as needed
0
FILENAME = 'C:/Users/th/Dropbox/com/MS1Ctt-P-temp.INP'
lines = list(open(FILENAME))
lines[95][2:8] = '99999'
open(FILENAME, 'w').write(''.join(lines))
-1

All Articles