【问题标题】:Python Consecutive Reads From FilePython 连续读取文件
【发布时间】:2015-07-21 20:32:23
【问题描述】:

我有一个从文件中读取的 Python 脚本。 第一个命令计算行数。第二个打印第二行,尽管第二个不工作。

lv_file = open("filename.txt", "rw+")

# count the number of lines =================================
lv_cnt = 0
for row in lv_file.xreadlines():
    lv_cnt = lv_cnt + 1

# print the second line =====================================
la_lines = la_file.readlines()
print la_lines[2]

lv_file.close()

当我这样写它时,它可以工作,但我不明白为什么我必须关闭文件并重新打开它才能让它工作。是否存在我滥用的某种功能?

lv_file = open("filename.txt", "rw+")

# count the number of lines =================================
lv_cnt = 0
for row in lv_file.xreadlines():
    lv_cnt = lv_cnt + 1

lv_file.close()

lv_file = open("filename.txt", "rw+")

# print the second line =====================================
la_lines = la_file.readlines()
print la_lines[2]

lv_file.close()

【问题讨论】:

  • la_lines[2] 不会让您进入第二行,而是会返回文件的 第三行

标签: python input readlines


【解决方案1】:

文件对象是一个迭代器。一旦你完成了所有的行,迭代器就会耗尽,进一步的读取将无济于事。

为避免关闭和重新打开文件,您可以使用seek 倒回到开头:

lv_file.seek(0)

【讨论】:

    【解决方案2】:

    你要的是file.seek():

    示例:基于您的代码

    lv_file = open("filename.txt", "rw+")
    
    # count the number of lines =================================
    lv_cnt = 0
    for row in lv_file.xreadlines():
        lv_cnt = lv_cnt + 1
    
    lv_file.seek(0)  # reset file pointer
    
    # print the second line =====================================
    la_lines = la_file.readlines()
    print la_lines[2]
    
    lv_file.close()
    

    这会将文件指针重置回它的起始位置。

    pydoc file.seek:

    seek(offset, whence=SEEK_SET) 将流位置更改为 给定的字节偏移量。偏移量是相对于位置解释的 由哪里表示。来自的值是:

    SEEK_SET 或 0 – 流的开始(默认);偏移量应该是 零或正 SEEK_CUR 或 1 - 当前流位置;抵消可能 为负 SEEK_END 或 2 – 流结束;偏移量通常是 负返回新的绝对位置。

    2.7 版中的新功能:SEEK_* 常量

    更新:一种更好的计数方法。文件中的行数迭代并且只关心第二行:

    def nth_line_and_count(filename, n):
        """Return the nth line in a file (zero index) and the no. of lines"""
    
        count = 0
    
        with open(filename, "r") as f:
            for i, line in enumerate(f):
                count += 1
                if i == n:
                    value = line
    
        return count, value
    
    nlines, line = nth_line_and_count("filename.txt", 1)
    

    【讨论】:

      【解决方案3】:

      由于 xreadlines() 保留指向它发送给您的最后一行的指针,所以当您这样做时

      la_lines = la_file.readlines()
      

      它基本上记住了它给你的最后一行的索引。 当您关闭文件然后打开它时,它会创建一个新的迭代器,并且它再次指向第 0 行。

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-09-27
      • 2011-04-17
      • 2020-05-25
      • 1970-01-01
      • 2014-01-29
      • 1970-01-01
      • 2021-02-10
      • 2016-10-21
      相关资源
      最近更新 更多