如何在txt文件中插入一些单词

时间:2016-10-28 04:39:07

标签: python-2.7

现在我想在文件中添加一些单词,但我只能通过使用f.open(' xxx.txt',&#39)在文件末尾添加一些单词(.txt) ;一个') 如果我使用' a +'模式,这些单词将从头开始发生。我希望在第一行插入一些句子而不更改原始句子。

# 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

我希望插入"鲍勃迪伦"在第一行,我要添加什么代码?

1 个答案:

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