0

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

    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

任何帮助,将不胜感激 !

4

2 回答 2

2

像这样试试

import fileinput

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

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

于 2013-07-03T03:42:29.050 回答
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”附加到每一行。

于 2013-07-03T04:07:08.920 回答