2016-10-28 7 views
0

이제 파일에 단어를 추가하고 싶지만 f.open ('xxx.txt')을 사용하여 파일 끝에 단어 (.txt) , 'a') 'a +'모드를 사용하면 단어가 처음부터 이전 단어로 바뀝니다. 나는 원래 문장을 바꾸지 않고 첫 줄에 몇 문장을 삽입하기를 희망한다.txt 파일에 단어를 삽입하는 방법

# using python 2.7.12 
    f = open('Bob.txt','w') 
    f.write('How many roads must a man walk down' 

    ' \nBefore they call him a man' 

    ' \nHow many seas must a white dove sail' 

    ' \nBefore she sleeps in the sand' 

    ' \nHow many times must the cannon balls fly' 

    " \nBefore they're forever banned" 

    " \nThe answer my friend is blowing in the wind" 

    " \nThe answer is blowing in the wind") 
    f.close() 
    # add spice to the song 
    f1 = open('Bob.txt','a') 
    f1.write("\n1962 by Warner Bros.inc.") 
    f1.close() 
    # print song 
    f2 = open('Bob.txt','r') 
    a = f2.read() 
    print a 

첫 번째 줄에 "Bob Dylan"을 삽입하고 싶습니다. 어떤 코드를 추가해야합니까?

답변

0

당신은 그렇게 할 수 없습니다. 당신은 파일을 읽을 수정하고 다시 작성해야합니다

with open('./Bob.txt', 'w') as f : 
    f.write('How many roads must a man walk down' 

     ' \nBefore they call him a man' 

     ' \nHow many seas must a white dove sail' 

     ' \nBefore she sleeps in the sand' 

     ' \nHow many times must the cannon balls fly' 

     " \nBefore they're forever banned" 

     " \nThe answer my friend is blowing in the wind" 

     " \nThe answer is blowing in the wind") 
# add spice to the song 
file = [] 
with open('Bob.txt', 'r') as read_the_whole_thing_first: 
    for line in read_the_whole_thing_first : 
     file.append(line) 
file = ["1962 by Warner Bros.inc.\n"] + file 
with open('Bob.txt', 'r+') as f: 
    for line in file: 
     f.writelines(line) 
with open('Bob.txt', 'r') as f2: 
    a = f2.read() 

print a 

결과 :

1962 by Warner Bros.inc. 
How many roads must a man walk down 
Before they call him a man 
How many seas must a white dove sail 
Before she sleeps in the sand 
How many times must the cannon balls fly 
Before they're forever banned 
The answer my friend is blowing in the wind 
The answer is blowing in the wind 
관련 문제