我有一个文本文件,其中包含以下内容:
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 ..
我之前曾经尝试过这样做,但我没有得到预期的结果。所以,首先我尝试编写一个代码,它只会在第一行的末尾附加"绝对人"。
所以,以下是我的代码:
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
第二行被覆盖。如何在一行末尾附加到一个字符串?
我想过以读取和附加模式打开文件,但它会覆盖现有文件。我不想从这个文件中读取字符串并通过附加将其写入另一个文件。如何附加或更改文件的行?
有什么方法可以在没有任何软件包的情况下做到这一点吗?
如果要写入同一文件,这是解决方案
file_lines = []
with open('test.txt', 'r') as file:
for line in file.read().split('n'):
file_lines.append(line+ ", absolutely man ..")
with open('test.txt', 'w') as file:
for i in file_lines:
file.write(i+'n')
如果您想写入其他文件,这是解决方案
with open('test.txt', 'r') as file:
for line in file.read().split('n'):
with open('test2.txt', 'a') as second_file:
second_file.write(line+ ", absolutely man ..n")
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)
尝试用 seek 写一些东西。 您只是重写而不是插入,因此您必须在编写文本后复制文件的末尾
jj = open('readwrite.txt', 'r+')
data = jj.read()
r_ptr = 0
w_ptr = 0
append_text = " Absolutely ..man n"
len_append = len(append_text)
for line in data.split("n"): #to see what I am getting
r_ptr += len(line)+1
w_ptr += len(line)
jj.seek(w_ptr)
jj.write(append_text+data[r_ptr:])
w_ptr += len_append