簡體   English   中英

從當前位置提取到文件結尾

[英]Extract from current position until end of file

我想從指定的行號提取文本文件中的所有數據,直到文件結尾。 這是我嘗試過的方法:

def extract_values(f):
    line_offset = []
    offset = 0
    last_line_of_heading = False

    if not last_line_of_heading:
        for line in f:
            line_offset.append(offset)
            offset += len(line)
            if whatever_condition:
                last_line_of_heading = True

    f.seek(0)

    # non-functioning pseudocode follows
    data = f[offset:]  # read from current offset to end of file into this variable

標題和我想要的數據之間實際上有一條空行,因此理想情況下我也可以跳過此行。

您事先知道電話號碼嗎? 如果是這樣的話,

def extract_values(f):
    line_number = # something
    data = f.readlines()[line_number:]

如果不是,則需要根據文件本身的內容確定行號,

def extract_values(f):
    lines = f.readlines()
    for line_number, line in enumerate(lines):
        if some_condition(line):
            data = lines[line_number:]
            break

如果文件很大(因為文件的行已加載到內存中),這將不是理想的選擇。 在這種情況下,您可能需要分兩次進行,而僅將文件數據存儲在第二次。

試試這個小的python程序LastLines.py

import sys

def main():
    firstLine = int(sys.argv[1])
    lines = sys.stdin.read().splitlines()[firstLine:]
    for curLine in lines:
        print curLine

if __name__ == "__main__":
    main()

輸入示例test1.txt:

a
b
c
d

用法示例:

python LastLines.py 2 < test1.txt

輸出示例:

c
d

該程序假定文件中的第一行是第0行。

您可以使用enumerate:

f=open('your_file')
for i,x in enumerate(f):
    if i >= your_line:
        #do your stuff

在這里,我將存儲從0開始的行號, x將包含該行

使用列表理解

[ x for i,x in enumerate(f) if i >= your_line ]

將在指定行之后為您提供行列表

使用字典理解

{ i:x for i,x in enumerate(f) if i >= your_line }

這將從指定的行號中為您提供行號作為鍵,並將行作為值。

您的if子句位置錯誤:

for line in f:
    if not last_line_of_heading:

考慮以下代碼:

def extract_values(f):
    rows = []
    last_line_of_heading = False

    for line in f:
        if last_line_of_heading:
            rows.append(line)
        elif whatever_condition:
            last_line_of_heading = True
    # if you want a string instead of an array of lines:
    data = "\n".join(rows)

暫無
暫無

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

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