【发布时间】:2018-06-24 11:29:39
【问题描述】:
我有一个文本文件,内容如下:
joe satriani is god
steve vai is god
steve morse is god
steve lukather is god
我想用python写一个代码,它会改变文件行,如:
joe satriani is god ,absolutely man ..
steve vai is god,absolutely man ..
steve morse is god,absolutely man ..
steve lukather is god,absolutely man ..
我之前尝试过这样做一次,但没有得到想要的结果。所以,首先我尝试编写一个代码,它只会在第一行的末尾附加“absolutely man”。
所以,下面是我的代码:
jj = open('readwrite.txt', 'r+')
jj.seek(1)
n = jj.read()
print(" yiuiuiuoioio \n") #just for debugging
print(n)
f = n.split("\n" , n.count("\n")) #to see what I am getting
print(f) #As it turns out read returns the whole content as a string
print(len(f[0])) # just for debugging
jj.seek(len(f[0])) #take it to the end of first line
posy = jj.tell() # to see if it actually takes it
print(posy)
jj.write(" Absolutely ..man ")
但在执行代码时,我的文件更改为以下内容:
joe satriani is god Absolutely ..man d
steve morse is god
steve lukather is god
第二行被覆盖。如何在一行末尾附加到一个字符串?
我想以读取和追加模式打开文件,但它会覆盖现有文件。我不想从此文件中读取字符串并通过附加将其写入另一个文件。如何追加或更改文件的行?
有没有什么方法可以不用包?
【问题讨论】: