如何在python中读取和添加字符串并写回每一行?

时间:2013-07-03 03:33:58

标签: python windows-7

我需要打开一个文件来读取每一行,然后在每行的末尾添加一个字符串。 然后,将新行写回打开的文件。

    number = 0 
    with open("test_openFile.txt", "r+b") as the_file:
    for line in the_file:
        print (line)
        type(line)
        line = line.strip('\n') + "\t" + str(number)
        number += 1
        the_file.write(line)

但是,我得到了:

  line = line.strip('\n')
  TypeError: Type str doesn't support the buffer API

任何帮助将不胜感激!

2 个答案:

答案 0 :(得分:2)

尝试这样

import fileinput

for line in fileinput.input("myfile.txt", inplace=1):
    print line.strip() + " a cool string"

将在每行的末尾添加“一个很酷的字符串”

答案 1 :(得分:0)

试试这个:

import os
fd_r=open('whatever.txt','r').readlines()
fd_w=open('whatever.txt','w')

for line in fd_r:
    line=line.strip()+" adding 1234"
    fd_w.write(line+"\n")
fd_w.close()  

这会将字符串“添加1234”附加到每一行。