Skip to content Skip to sidebar Skip to footer

Appending Data In A Specific Line Of Text In A File Python

Suppose I have a file like this: words words 3245, 3445, 345634, 345678 I am wondering if it is possible to add data onto the 4th line of the code so the out put is this: words w

Solution 1:

You can achieve that by doing this

# define a function so you can re-use it for writing to other specific lines
def writetoendofline(lines, line_no, append_txt):
    lines[line_no] = lines[line_no].replace('\n', '') + append_txt + '\n'

# open the file in read mode to read the current input to memory
with open('./text', 'r') as txtfile:
    lines = txtfile.readlines()

# in your case, write to line number 4 (remember, index is 3 for 4th line)   
writetoendofline(lines, 3, ' 67899')

# write the edited content back to the file
with open('./text', 'w') as txtfile:
    txtfile.writelines(lines)

# close the file
txtfile.close()

Post a Comment for "Appending Data In A Specific Line Of Text In A File Python"