簡體   English   中英

Python從文件連續讀取

[英]Python Consecutive Reads From File

我有一個從文件讀取的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()

文件對象是迭代器。 遍歷所有行之后,迭代器就筋疲力盡,進一步的讀取將無濟於事。

為了避免關閉和重新打開文件,可以使用seek快退到開頭:

lv_file.seek(0)

您追求的是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)將流位置更改為給定的字節偏移量。 offset相對於wherece指示的位置進行解釋。 其中的值是:

SEEK_SET或0 –流的開始(默認); 偏移量應為零或正SEEK_CUR或1 –當前流位置; offset可以為負SEEK_END或2 –流的結尾; offset通常為負返回新的絕對位置。

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)

由於xreadlines()保留指向它發送給您的最后一行的指針,因此當您執行

la_lines = la_file.readlines()

它基本上會記住它給您的最后一行的索引。 當您關閉文件然后再打開它時,它將創建一個新的迭代器,並再次指向第0行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM