【问题标题】:Append to a file after nth byte in python在python中的第n个字节后附加到文件
【发布时间】:2013-09-16 23:19:54
【问题描述】:

我需要在第 n 个字节之后追加到文件中,而不删除之前的内容。

例如, 如果我有一个文件包含:“Hello World”
我寻求位置(5)写“这个”我应该得到
“你好这个世界”

有什么模式可以打开文件吗??

目前我的代码替换了字符
并给出“Hello thisd”

>>> f = open("1.in",'rw+')
>>> f.seek(5)
>>> f.write(' this')
>>> f.close()

有什么建议吗?

【问题讨论】:

  • 文件抽象一般不支持“插入”。您将不得不重写文件的其余部分,或者找到更高级别的抽象(这将为您完成这项工作)。
  • 我在没有完全理解问题的情况下添加了一个答案(现已删除)。您想要的有两个标准答案:a)对于大数据,使用数据库,例如sqlite,以及 b) 对于小数据,读取文件,执行内存插入,然后重写文件。

标签: python file


【解决方案1】:

您无法在文件中insert。通常做的是:

  1. 有两个缓冲区,旧文件和要添加内容的新文件
  2. 从旧内容复制到新内容,直到您要插入新内容为止
  3. 在新文件中插入新内容
  4. 继续从旧缓冲区写入新缓冲区
  5. (可选)将旧文件替换为新文件。

在python中应该是这样的:

nth_byte = 5
with open('old_file_path', 'r') as old_buffer, open('new_file_path', 'w') as new_buffer:
    # copy until nth byte
    new_buffer.write(old_buffer.read(nth_byte))
    # insert new content
    new_buffer.write('this')
    # copy the rest of the file
    new_buffer.write(old_buffer.read())

现在你必须在new_buffer 中有Hello this world。之后,由你决定是用新的覆盖旧的还是你想用它做什么。

希望这会有所帮助!

【讨论】:

    【解决方案2】:

    我认为您要做的是读取文件,将其分成两块,然后重写。比如:

    n = 5
    new_string = 'some injection'
    
    with open('example.txt','rw+') as f:
        content = str(f.readlines()[0])
        total_len = len(content)
        one = content[:n]
        three = content[n+1:total_len]
        f.write(one + new_string + three)
    

    【讨论】:

      【解决方案3】:

      您可以使用mmap 执行以下操作:

      import mmap
      
      with open('hello.txt', 'w') as f:
          # create a test file
          f.write('Hello World')
      
      with open('hello.txt','r+') as f:
          # insert 'this' into that 
          mm=mmap.mmap(f.fileno(),0)
          print mm[:]
          idx=mm.find('World')
          f.write(mm[0:idx]+'this '+mm[idx:])
      
      with open('hello.txt','r') as f:  
          # display the test file  
          print f.read()
          # prints 'Hello this World'
      

      mmap 允许您将 a 视为可变字符串。但它有限制,例如切片分配必须与长度相同。您可以在 mmap 对象上使用正则表达式。

      底线,要在文件流中插入字符串,你需要读取它,将字符串插入到读取的数据中,然后再写回。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-10-04
        • 2015-07-13
        • 2020-02-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多