2013-05-20 3 views
2

온라인 설문 조사를하고 txt 파일의 모든 입력을 추적합니다.어떻게 여러 줄이있는 txt 파일에 쓸 수 있습니까?

다음은 두 가지 질문이며 다른 사람이 질문에 답변 할 때마다 해당 질문에 답을 추가하려고합니다.

이 내가 지금까지 내 txt 파일에있는 모든입니다 :

0, 1-5, 어떻게 오늘 기분의 규모에 3,5,4,5,4,3,

1, 수면, 술, 대화, TV를, 당신의 기분을 향상 먹을 수있는 활? 뭐,

내 질문은 : 어떻게 내가 대신 파일의 첫 번째 줄에 데이터를 추가하기 위해 파이썬을 사용할 수 있습니다 둘째?

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

는 두 번째 줄에 '5'추가합니다,하지만 난 그 결과를 원하는가 첫 번째 질문에 adde 될 : 내가 할 경우처럼

.

+0

하십시오, 모드 대신에 파일에 무언가를 추가 할 볼 수 있습니다 http://stackoverflow.com/questions/을 4719438/edit-specific-line-in-text-file-in-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)) 
관련 문제