从原地删除文件中的一行 [英] Delete a line from a file in-place

查看:112
本文介绍了从原地删除文件中的一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个.txt,我想要一个python脚本来处理它。

I have a .txt and i want a python script to do something with it.

我的.txt看起来像这样:

My .txt looks something like this:


  • 27b23815-4cbb-dfae-3e6d-38f67ec4266e

  • 81a090bd-8973-bc37-5c7b-dc1a18e8ddee

  • 7e1bf596-88bc-d8fd-9aea-278d5c689eaa

  • 0b365fb0-dea4-53a1-fd27-6cbf9721602c

  • 1c317dcf-73f4-edf5 -b6a1-ad663d2b507e

  • 6db8342d-1afb-2777-1a7f-a5daad06d2db

  • 27b23815-4cbb-dfae-3e6d-38f67ec4266e
  • 81a090bd-8973-bc37-5c7b-dc1a18e8ddee
  • 7e1bf596-88bc-d8fd-9aea-278d5c689eaa
  • 0b365fb0-dea4-53a1-fd27-6cbf9721602c
  • 1c317dcf-73f4-edf5-b6a1-ad663d2b507e
  • 6db8342d-1afb-2777-1a7f-a5daad06d2db

我想要删除.txt的第一行,如果在第6行写入了某些内容,但所有内容都没有创建新的.txt。不能完全掌握这个:(

And i want to delete the first line of the .txt if there is something writen in the 6th line but all without making a new .txt out of the old. Can't quite get the hang of this :(

我知道我可以删除第一行:

I know i can delete the first Line with:

       lines = file(idpath, "r").readlines()  
       del lines[0]  
       file(idpath,"w").writelines(lines) 

感谢任何帮助

推荐答案

由于文件范例是一个(可调整大小的)字节数组,因此您不能简单地从内部删除数据。而是执行以下任一操作:

Since the file paradigm is a (resizable) array of bytes, you cannot simply delete data from inside. Instead, you do either of the following:


  • 滑回要删除的片段后的所有数据以覆盖它,然后调整文件的大小

    (老式的,通常用于内存映射文件或当您无法负担另一份数据副本时)

  • 将所有结果数据写入新文件,然后将其移到旧文件上< br>
    (典型的批处理,因为 move 在同一个文件系统中是原子的和即时的,可能有效(取决于th) e OS)即使文件被其他东西打开,你也可以在应用更改之前检查结果。

  • 读取你需要保存到内存中的所有数据,然后将文件截断为零字节并写入新数据

    (典型的文本编辑器。该文件无法通过其他内容进行打开,当您截断该文件时,旧内容将丢失。 OTOH,你不需要创建另一个文件的权限并覆盖这个文件)

  • slide back all the data following the fragment to be deleted to overwrite it, then adjust the file's size
    (old-fashioned, typically used with memory-mapped files or when you can't afford another copy of the data)
  • write all the resulting data to a new file, then move it over the old one
    (typical in batch processing since move is atomic and instant within the same filesystem, may work (depending on the OS) even if the file is open by something else, and you can check the results before applying the change)
  • read all the data you need to preserve into memory, then truncate the file to zero bytes and write the new data
    (typical for text editors. The file cannot be open for writing by something else and the moment you truncate it, the old contents are lost. OTOH, you don't need the permissions to create another file and overwrite this one)

至于列表操作, RTM 序列类型

As for list manipulations, RTM Sequence types.

这篇关于从原地删除文件中的一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆