Text files are problematic to rewrite because they often have variable length records, however yours is fixed length, so:
fh = open('gash.txt','r+')
# read the first line
line = fh.readline()
row = line.split(' - ')
fourthValue = row[3]
newFourthValue = '4'
newLine = line.replace(fourthValue, newFourthValue)
At this point the "current file position" is at the start of the next line, so we have to move it back to the start of the current record
fh.seek(0)
fh.write(newLine)
fh.close()
That is very simplistic. The line is question is the first line. If it was anywhere else we would have to remember the file position before each line by using fh.tell()
, then using that number in the fh.seek()
.
EDIT:
In reply to the question "If I wanted to replace a value in the 4th line not the first", this replaces the 4 with an 8 on the fourth line.
lineToChange = 4
fieldToChange = 3
newValue = '8'
sep = ' - '
lineno = 0
fh = open('gash.txt','r+')
while True:
# Get the current file position
start_pos = fh.tell()
# read the next line
line = fh.readline()
if not line: break # exit the loop at EOF
lineno += 1
if lineno == lineToChange:
row = line.split(sep)
# A different replace mechanism
row[fieldToChange] = newValue
newLine = sep.join(row)
# before writing, we must move the file position
fh.seek(start_pos)
fh.write(newLine)
fh.close()
Please note this only works because we are replacing a single character with another single character. If we wanted to replace, say, 8 with 10 then this would not work, because now the line length would be different and we would overwrite the start of the next line.