0

I am trying to add a text in a line while looping the file in append and read mode. Below is the code that does not work i.e. does not write the text in the middle of loop line.

file = open('path/to/file.txt','a+')
file.seek(0, 0)
line=file.readline()
while line:
    if line=="2ND LINE":
        file.write(",new text")
    line=file.readline()
file.close()

What I am trying to do:

1ST LINE
2ND LINE,new text
3RD LINE
Dhay
  • 585
  • 7
  • 29
  • @DarrylG. Unfortunately Yes. But it is not a solution but a fact from line 'The reason for this is that textfiles are not designed for random access' from the answer. – Dhay Mar 12 '21 at 12:28
  • @Dhay--retracted my close vote. – DarrylG Mar 12 '21 at 12:40

2 Answers2

1

Comparing a line like this is probably not going to work due to line endings. You either need to check if the line equals 2ND LINE\n or do a comparison differently like so if "2ND LINE" in line:

But you can do it something like this:

import fileinput
for line in fileinput.FileInput('path/to/file.txt', inplace=1):
    if "2ND LINE" in line:
        line = line.replace(line, line.strip() + ",new text\n")
    print(line, end='')

Adapted from here.

JostB
  • 126
  • 4
1

I think that you can only accomplish what you want by reading the entire file and then rewriting it:

#soInsertTextInFile
with open('file3.txt','r') as file:
    lines = file.read().split('\n')

with open('file3.txt','w') as file:
    fileLines = 1
    for line in lines:
        print(line)
        file.write(line)
        if fileLines == 2:
            print('write') 
            file.write(",new text")
        file.write('\n')
        fileLines += 1

Output as requested.

btw this program counts the lines. You may want a different test to decide when to append something to the current line.

quamrana
  • 37,849
  • 12
  • 53
  • 71