2

私はオンライン調査を行い、すべての入力を txt ファイルに記録しています。

以下は 2 つの質問です。誰かが質問に答えるたびに、対応する質問に回答を追加したいと思います。

これは、これまでのtxtファイルにあるすべてです。

0, 1 から 5 のスケールで、今日の気分はどうですか?,3,5,4,5,4,3,

1, 気分を良くするためにできることは?,食べる,寝る,飲む,話す,テレビ,

私の質問は次のとおりです。Pythonを使用して、ファイルの2行目ではなく1行目にデータを追加するにはどうすればよいですか?

私がする場合のように:

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

2行目に「5」が追加されますが、その結果を最初の質問に追加したいと思います。

4

3 に答える 3

0

モードでファイルに何かを追加できます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))
于 2013-05-20T22:11:12.723 に答える