简体   繁体   English

我如何从特定点开始阅读文本文件?

[英]How do i start reading a text file from a specific point?

So my question is basically, how do i start reading a file from a specific line, like for example line 14 until line 18?所以我的问题基本上是,我如何从特定行开始读取文件,例如第 14 行到第 18 行?

Im working on a simple ContactList app and the only thing missing is deleting the information from a specific name.我正在开发一个简单的 ContactList 应用程序,唯一缺少的是删除特定名称的信息。 The user can create a new contact which has a name, a number and an address as information.用户可以创建一个新联系人,该联系人具有姓名、号码和地址作为信息。 I want the user to also be able to delete the data of that person by typing in their name.我希望用户也能够通过输入他们的名字来删除那个人的数据。 Then, the program should read the name and all of the 4 lines under it and remove them from the text File.然后,程序应读取名称及其下的所有 4 行,并将它们从文本文件中删除。 How could i achieve this?我怎么能做到这一点?

You can't.你不能。 You need to read the first n lines in order to find out which line has which number.您需要阅读前 n 行才能找出哪一行有哪个数字。 Except if your records have a fixed length per line (which is not a good idea - there's always someone with a longer name that you could think of).除非你的记录每行有固定的长度(这不是一个好主意 - 总有你能想到的名字更长的人)。

Likewise, you can't delete a line from the text file.同样,您不能从文本文件中删除一行。 The space on disk does not move by itself.磁盘上的空间不会自行移动。 You need an algorithm that implements safe saving and rearranges the data:您需要一个实现安全保存和重新排列数据的算法:

foreach line in input_file:
    if line is needed:
        write line to temporary_output_file
    else:
        ignore (don't write = delete)
delete input_file
move temporary_output_file to input_file

Disadvantage: you need about double the disk space while input_file and temporary_output_file both exist.缺点:当 input_file 和 temporary_output_file 都存在时,你需要大约两倍的磁盘空间。

With safe saving, the NTFS file system driver will give the moved file the same time stamp that it had before deleting the file.通过安全保存,NTFS 文件系统驱动程序将为移动的文件提供与删除文件之前相同的时间戳。 Read the Windows Internals 7 book (should be part 2, chapter 11) to understand it in detail.阅读Windows Internals 7 书(应该是第 2 部分,第 11 章)以详细了解它。

Depending on how large the contact list is (probably it's less than 10M entries), there's no problem of loading the whole database into memory, deleting the record and then writing everything back.根据联系人列表的大小(可能少于 10M 个条目),将整个数据库加载到 memory 中,删除记录然后再写回所有内容是没有问题的。

You can jump to any offset within a file.您可以跳转到文件中的任何偏移量。 However, there isn't any way to know where a particular line begins unless you know the length of every line.但是,除非您知道每行的长度,否则无法知道特定行的起始位置。

If you are writing a contact app, you should not use a regular text file unless:如果您正在编写联系人应用程序,则不应使用常规文本文件,除非:

  1. You pad line lengths so that you can easily calculate the position of each line.您填充行长度,以便您可以轻松计算每行的 position。
  2. You are loading the entire file into memory.您正在将整个文件加载到 memory。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM