【问题标题】:Writing to a file which is open in read and write mode altering the structure写入以读写模式打开的文件会改变结构
【发布时间】:2018-06-24 11:29:39
【问题描述】:

我有一个文本文件,内容如下:

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 ..

我之前尝试过这样做一次,但没有得到想要的结果。所以,首先我尝试编写一个代码,它只会在第一行的末尾附加“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

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

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

有没有什么方法可以不用包?

【问题讨论】:

    标签: python file io


    【解决方案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")
    

    【讨论】:

      【解决方案2】:
      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)
      

      【讨论】:

      • 谢谢,您的答案更具可读性和初学者友好性,所以我会说它更好
      • 是的,但你男人你!...非常感谢你的回答:) 刚刚睁开眼睛
      【解决方案3】:

      试图用 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
      

      【讨论】:

      • 我输入如下:joe is god steve v is god steve m is god steve l is god
      • 我得到的输出是:joe is god Absolutely ..man steve v is go Absolutely ..man steve m is go Absolutely ..man steve l is God Absolutely ..man
      • 我不知道问题出在哪里。它对我来说很好
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-27
      • 2023-04-05
      相关资源
      最近更新 更多