<p>我有一个文本文件,它包含以下内容:</p>
<pre><code>joe satriani is god
steve vai is god
steve morse is god
steve lukather is god
</code></pre>
<p>我想用python编写一段代码,它会改变文件行,比如:</p>
^{pr2}$
<p>我曾试过这么早做过一次,但没有得到预期的结果。我只想在第一行的末尾加上一个代码。在</p>
<p>下面是我的代码:</p>
<pre><code>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 ")
</code></pre>
<p>但在执行代码时,我的文件将更改为以下内容:</p>
<pre><code>joe satriani is god Absolutely ..man d
steve morse is god
steve lukather is god
</code></pre>
<p>第二行被覆盖。如何在一行末尾附加一个字符串?在</p>
<p>我想在read-and-append模式下打开文件,但它会覆盖现有的文件。我不想从这个文件中读取字符串,并通过附加将写入另一个文件。如何追加或修改文件的行?在</p>
<p>有没有办法不带任何包裹?在</p>
<pre><code>given_str = 'absolutely man ..'
text = ''.join([x[:-1]+given_str+x[-1] for x in open('file.txt')])
with open('file.txt', 'w') as file:
file.write(text)
</code></pre>