2016-10-28 5 views
0

これで、ファイルにいくつかの単語を追加したいのですが、f.open( 'xxx.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 
関連する問題