如何写入多行的txt文件?

时间:2013-05-20 21:15:56

标签: python file append lines

我进行了在线调查,并跟踪txt文件中的所有输入。

以下是两个问题,每当有人回答问题时,我想在相应的问题上附上答案。

到目前为止,这是我在txt文件中的全部内容:

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

1,什么活动可以改善你的心情?,吃饭,睡觉,喝酒,聊天,看电视,

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

如果我这样做:

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

它会将'5'追加到第二行,但我希望将结果添加到第一个问题上。

3 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分: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()

答案 2 :(得分: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))
相关问题