写入以读写模式打开的文件,更改结构

时间:2018-06-24 11:29:40

标签: python file io

我有一个文本文件,其中包含以下内容:

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

第二行被覆盖。如何在一行的末尾追加到一个字符串?

我想到了以读取和追加模式打开文件,但是它将覆盖现有文件。我不想从此文件中读取字符串,并通过追加将其写入另一个文件。如何添加或更改文件的行?

有没有包装的方法吗?

3 个答案:

答案 0 :(得分:1)

这是您要写入同一文件的解决方案

  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")

答案 1 :(得分:1)

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)

答案 2 :(得分:0)

试图用寻求来写点东西。您只是重写而不是插入,因此在写完文本后必须复制文件的结尾

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