简体   繁体   English

如何通过从python中的另一个文本文件中查找位置来打印文件中的行?

[英]how to print lines in a file by seeking a position from another text file in python?

This is my code for getting lines from a file by seeking a position using f.seek() method but I am getting a wrong output. 这是我的代码,用于通过使用f.seek()方法寻找位置来从文件中获取行,但是我得到了错误的输出。 it is printing from middle of the first line. 它是从第一行的中间开始打印的。 can u help me to solve this please? 你能帮我解决这个问题吗?

f=open(r"sample_text_file","r")
last_pos=int(f.read())
f1=open(r"C:\Users\ddadi\Documents\project2\check\log_file3.log","r")
f1.seek(last_pos)
for i in f1:
    print i
    last_position=f1.tell()
    with open('sample_text.txt', 'a') as handle:
        handle.write(str(last_position))

sample_text file contains the file pointer offset which is returned by f1.tell() sample_text文件包含文件指针偏移量,该偏移量由f1.tell()返回

If it's printing from the middle of a line that's almost certainly because your offset is wrong. 如果是从一行的中间开始打印,那几乎可以肯定是因为您的胶印错误。 You don't explain how you came by the magic number you use as an argument to seek , and without that information it's difficult to help more precisely. 您无需解释如何使用用作搜索参数的幻数来seek ,而没有这些信息,很难更精确地提供帮助。

One thing is, however, rather important. 然而,一件事很重要。 It's not a very good idea to use seek on a file that is open in text mode (the default in Python). 在以文本模式(Python中的默认设置)打开的文件上使用seek并不是一个好主意。 Try using open(..., 'rb') and see if the process becomes a little more predictable. 尝试使用open(..., 'rb') ,看看该过程是否变得更具可预测性。 It sounds as though you may have got the offset by counting characters after reading in text mode, but good old Windows includes carriage return characters in text files, which are removed by the Python I/O routines before your program sees the text. 听起来好像您是通过在文本模式下阅读后对字符进行计数来获得偏移量的,但是好的老式Windows在文本文件中包含了回车符,这些字符在您的程序看到文本之前已被Python I / O例程删除。

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

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