2

I made an online survey and I keep track of all the inputs in a txt file.

Below are two questions, and everytime someone answers a question, I want to append the answer to the coresponding question.

This is all i have in my txt file so far:

0, On a scale of 1-5, how are you feeling today?,3,5,4,5,4,3,

1, What activites can improve your mood?,eat,sleep,drink,talk,tv,

My question is : How can i use python to append a data into the first line of the file instead of the second?

Like if i do:

f= open ('results.txt','a')
f.write ('5')
f.close ()

it will append '5' to the second line, but I want that result to be adde onto the first question.

  • Please, see similar questions http://stackoverflow.com/questions/4719438/editing-specific-line-in-text-file-in-python and http://stackoverflow.com/questions/14340283/how-to-write-to-a-specific-line-in-file-in-python. – alecxe May 20 '13 at 21:18
  • 2
    consider using [shelve](http://docs.python.org/2/library/shelve.html#module-shelve) or [sqlite](http://docs.python.org/2/library/sqlite3) instead of hacking your own serialization file format – Thomas Fenzl May 20 '13 at 21:21

3 Answers3

0

You can't insert data in the middle of a file. You have to rewrite the file.

Lennart Regebro
  • 167,292
  • 41
  • 224
  • 251
0

You can try this way:

>>> d = open("asd")
>>> dl = d.readlines()
>>> d.close()
>>> a = open("asd", 'w')
>>> dl = dl[:1] + ["newText"] + dl[1:]
>>> a.write("\n".join(dl))
>>> a.close()
gariel
  • 687
  • 3
  • 13
0

You can add something in the file in place with mode rb+

import re

ss = '''
0, On a scale of 1-5, how are you feeling today?,3,5,4,5,4,3,

1, What activities can improve your mood?,eat,sleep,drink,talk,tv,

2, What is worse condition for you?,humidity,dry,cold,heat,
'''

# not needed for you
with open('tryy.txt','w') as f:
    f.write(ss)


# your code
line_appendenda = 1
x_to_append = 'weather'

with open('tryy.txt','rb+') as g:
    content = g.read()
    # at this stage, pointer g is at the end of the file
    m = re.search('^%d,[^\n]+$(.+)\Z' % line_appendenda,
                  content,
                  re.MULTILINE|re.DOTALL)
    # (.+) defines group 1
    # thanks to DOTALL, the dot matches every character
    # presence of \Z asserts that group 1 spans until the
    # very end of the file's content
    # $ in ther pattern signals the start of group 1
    g.seek(m.start(1))
    # pointer g is moved back at the beginning of group 1
    g.write(x_to_append)
    g.write(m.group(1))
eyquem
  • 26,771
  • 7
  • 38
  • 46