我有一个文本文件,它包含以下内容:
joe satriani is god
steve vai is god
steve morse is god
steve lukather is god
我想用python编写一段代码,它会改变文件行,比如:
^{pr2}$我曾试过这么早做过一次,但没有得到预期的结果。我只想在第一行的末尾加上一个代码。在
下面是我的代码:
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
第二行被覆盖。如何在一行末尾附加一个字符串?在
我想在read-and-append模式下打开文件,但它会覆盖现有的文件。我不想从这个文件中读取字符串,并通过附加将写入另一个文件。如何追加或修改文件的行?在
有没有办法不带任何包裹?在
如果您想写入同一个文件,这就是解决方案
这是一个解决方案,如果你想写到另一个文件
^{pr2}$试着用seek写东西。你只是重写而不是插入,所以你必须在写完你的文本后复制文件的结尾
相关问题 更多 >
编程相关推荐