2

我进行了一项在线调查,并在一个 txt 文件中记录了所有输入。

以下是两个问题,每次有人回答问题时,我都想将答案附加到对应的问题中。

到目前为止,这就是我的 txt 文件中的所有内容:

0,在1-5的范围内,你今天感觉如何?,3,5,4,5,4,3,

1,什么活动可以改善你的情绪?,吃,睡,喝,说话,看电视,

我的问题是:如何使用 python 将数据附加到文件的第一行而不是第二行?

就像我这样做:

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

它会将“5”附加到第二行,但我希望将该结果添加到第一个问题中。

4

3 回答 3

0

你可以这样试试:

>>> 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()
于 2013-05-20T21:40:03.710 回答
0

您不能在文件中间插入数据。你必须重写文件。

于 2013-05-20T21:23:37.507 回答
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 回答