2013-05-20 170 views
2

我做了在線調查,並跟蹤txt文件中的所有輸入。如何寫入多行文本文件?

下面是兩個問題,每次有人回答一個問題時,我想將答案附加到相關問題。

這是所有我在我的txt文件至今:

0,在1-5,你今天怎麼感覺規模,3,5,4,5,4,3,

1,什麼activites可以改善你的情緒,吃飯,睡覺,喝水,說話,電視,

我的問題是:我如何可以使用Python的數據附加到文件的第一行,而不是第二?

一樣,如果我做的:

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

它會追加「5」到第二行,但我想這個結果被阿迪到的第一個問題。

+0

請參閱類似的問題http://stackoverflow.com/questions/ 4719438 /編輯特定的文本文件在python和http://stackoverflow.com/questions/14340283/how-to-write-to-a-specific-line-in-file-in-蟒蛇。 – alecxe

+2

考慮使用[shelve](http://docs.python.org/2/library/shelve.html#module-shelve)或[sqlite](http://docs.python.org/2/library/sqlite3)而不是破解你自己的序列化文件格式 –

回答

0

您不能在文件中插入數據。你必須重寫這個文件。

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() 
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))