-2

I want to insert a text specifically before a line 'Number'.

I want to insert 'Hello Everyone' befor the line starting with 'Number'

My code:

import re
result = []
with open("text2.txt", "r+") as f:
    a = [x.rstrip() for x in f] # stores all lines from f into an array and removes "\n"
    # Find the first occurance of "Centre" and store its index
    for item in a:
        if item.startswith("Number"): # same as your re check
            break
    ind = a.index(item) #here it produces index no./line no.
    result.extend(a[:ind])
        f.write('Hello Everyone')

tEXT FILE:

QWEW
RW
...
Number hey
Number ho

Expected output:

QWEW
RW
...
Hello Everyone
Number hey
Number ho

Please help me to fix my code:I dont get anything inserted with my text file!Please help! Answers will be appreciated!

asey raam
  • 23
  • 1
  • 3

3 Answers3

2

The problem

When you do open("text2.txt", "r"), you open your file for reading, not for writing. Therefore, nothing appears in your file.

The fix

Using r+ instead of r allows you to also write to the file (this was also pointed out in the comments. However, it overwrites, so be careful (this is an OS limitation, as described e.g. here). The following should do what you desire: It inserts "Hello everyone" into the list of lines and then overwrites the file with the updated lines.

with open("text2.txt", "r+") as f:
    a = [x.rstrip() for x in f]
    index = 0
    for item in a:
        if item.startswith("Number"):
            a.insert(index, "Hello everyone") # Inserts "Hello everyone" into `a`
            break
        index += 1
    # Go to start of file and clear it
    f.seek(0)
    f.truncate()
    # Write each line back
    for line in a:
        f.write(line + "\n")
hlt
  • 6,219
  • 3
  • 23
  • 43
2

The correct answer to your problem is the hlt one, but consider also using the fileinput module:

import fileinput

found = False
for line in fileinput.input('DATA', inplace=True):
    if not found and line.startswith('Number'):
        print 'Hello everyone'
        found = True
    print line,
Community
  • 1
  • 1
enrico.bacis
  • 30,497
  • 10
  • 86
  • 115
1

This is basically the same question as here: they propose to do it in three steps: read everything / insert / rewrite everything

with open("/tmp/text2.txt", "r") as f:
lines = f.readlines()

for index, line in enumerate(lines):
    if line.startswith("Number"):
        break
lines.insert(index, "Hello everyone !\n")

with open("/tmp/text2.txt", "w") as f:
    contents = f.writelines(lines)
Community
  • 1
  • 1
Zulko
  • 3,540
  • 1
  • 22
  • 18