Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/319.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何从最后一个位置重复读取文件_Python_File_File Io - Fatal编程技术网

Python 如何从最后一个位置重复读取文件

Python 如何从最后一个位置重复读取文件,python,file,file-io,Python,File,File Io,我试图反复读取系统日志,并且只从上次读取时停止的点开始。我试图保存tell()的位置,它是一个高速文件,每次读取之前都要重新加载以查找 lf = open("location.file", 'r') s = lf.readline() last_pos = int(s.strip()) lf.close() sl = open("/var/log/messages", 'r') sl.seek(last_pos) for line i

我试图反复读取系统日志,并且只从上次读取时停止的点开始。我试图保存tell()的位置,它是一个高速文件,每次读取之前都要重新加载以查找



    lf = open("location.file", 'r')
    s = lf.readline()
    last_pos = int(s.strip())
    lf.close()

    sl = open("/var/log/messages", 'r')
    sl.seek(last_pos)
    for line in sl.readlines():
         # This should be the starting point from the last read
    last_loc = sl.tell()

    lf = open("location.file", "w+")
    lf.write(last_loc)
    lf.close()

  • str(last\u loc)
    而不是
    last\u loc

    其余的可能是可选的

  • 使用
    w
    而不是
    w+
    来写入位置
  • 完成后关闭
    /var/log/messages
  • 根据您的Python版本(当然是2.6或更高版本,可能是2.5版本,具体取决于),您可能希望将
    一起使用来自动关闭文件
  • 如果只是编写值,则可能不需要
    strip
  • 您可以在
    lf
    上使用
    read
    而不是
    readline
  • 对于
    sl
    ,您可以迭代文件本身,而不是使用
    readlines

    try:
        with open("location.file") as lf:
            s = lf.read()
            last_pos = int(s)
    except:
        last_post = 0
    
    with open("/var/log/messages") as sl:
        sl.seek(last_pos)
        for line in sl:
            # This should be the starting point from the last read
        last_loc = sl.tell()
    
    with open("location.file", "w") as lf:
        lf.write(str(last_loc))
    

  • 你的阅读线很奇怪。您需要做的是:

    1) 将值另存为字符串并对其进行分析:

    lf.write(str(last_loc))
    
    2) 将位置保存为int并重新读取:

    lf.write(struct.pack("Q",lf.tell()))
    last_pos = struct.unpack("Q",lf.read())
    

    仍然没有告诉他如何将int写入文件:)
    try:with open(“location.file”)为lf:s=lf.read()last\u pos=int(s),除了:last\u pos=0你必须在评论中使用反勾号,但除此之外,这是一个很好的建议。