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

2024-06-24 13:26:01 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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模式下打开文件,但它会覆盖现有的文件。我不想从这个文件中读取字符串,并通过附加将写入另一个文件。如何追加或修改文件的行?在

有没有办法不带任何包裹?在


Tags: 文件to代码readmorseisitsteve
3条回答

如果您想写入同一个文件,这就是解决方案

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

这是一个解决方案,如果你想写到另一个文件

^{pr2}$

试着用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
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)

相关问题 更多 >