I need to open a file to read each line, then add a string at the end of each line. And then, write back the new line the opened file.
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)
But, I got:
line = line.strip('\n')
TypeError: Type str doesn't support the buffer API
Any help would be appreciated !
Try it like this
import fileinput
for line in fileinput.input("myfile.txt", inplace=1):
print line.strip() + " a cool string"
that will add " a cool string" to the end of every line
Try this:
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()
This will append the string " adding 1234" to every line.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.