写入以读写模式打开的文件,从而改变结构 [英] Writing to a file which is open in read and write mode altering the structure
问题描述
我有一个文本文件,其中包含以下内容:
I have a text file, which has the following, contents:
joe satriani is god
steve vai is god
steve morse is god
steve lukather is god
我想用python编写代码,这将更改文件行,例如:
I wanted to write a code in python, which will change the file lines like:
joe satriani is god ,absolutely man ..
steve vai is god,absolutely man ..
steve morse is god,absolutely man ..
steve lukather is god,absolutely man ..
我曾经尝试过这样做一次,但没有得到理想的结果.因此,首先,我尝试编写代码,该代码只会在第一行的末尾附加绝对是男人".
I had tried doing such earlier once and I had not gotten the desired outcome. So, first I tried writing a code, which would just append "absolutely man" at the end of only the first line.
因此,以下是我的代码:
So, the following is my 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 ")
但是在执行代码时,我的文件更改为以下内容:
But on executing the code, my file changes to the following:
joe satriani is god Absolutely ..man d
steve morse is god
steve lukather is god
第二行被覆盖.如何在一行的末尾附加到一个字符串?
The second line is being overwritten. How to append to one string at the end of one line?
我想到了以读取和追加模式打开文件,但是它将覆盖现有文件.我不想从该文件中读取字符串,并通过追加将其写入另一个文件.如何添加或更改文件的行?
I thought of opening the file in read and append mode but it would overwrite the existing file. I do not want to read strings from this file and write the into another file by appending. How to append or alter the lines of a file?
有没有包装的方法吗?
推荐答案
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)
这篇关于写入以读写模式打开的文件,从而改变结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!