簡體   English   中英

使用 readline 限制讀取的數量

[英]Limiting amount read using readline

我正在嘗試讀取大文本文件的前 100 行。 執行此操作的簡單代碼如下所示。 但是,挑戰在於我必須防范沒有任何換行符的損壞或其他扭曲文件的情況(是的,人們以某種​​方式想出了生成這些文件的方法)。 在這些情況下,我仍然想讀入數據(因為我需要查看那里發生了什么),但將其限制為 n 個字節。

我能想到的唯一方法是逐個字符讀取文件。 除了速度慢(可能只有 100 行不是問題)我擔心當我遇到使用非 ASCII 編碼的文件時會遇到麻煩。

是否可以限制使用 readline() 讀取的字節數? 或者有沒有更優雅的方法來處理這個問題?

line_count = 0
with open(filepath, 'r') as f:
    for line in f:
        line_count += 1
        print('{0}: {1}'.format(line_count, line))
        if line_count == 100:
            break

編輯:

正如@Fredrik 正確指出的那樣, readline() 接受一個限制讀取字符數的參數(我認為這是一個緩沖區大小參數)。 因此,就我的目的而言,以下內容非常有效:

max_bytes = 1024*1024
bytes_read = 0

fo = open(filepath, "r")
line = fo.readline(max_bytes)
bytes_read += len(line)
line_count = 0
while line != '':
    line_count += 1
    print('{0}: {1}'.format(line_count, line))
    if (line_count == 100) or (bytes-read >= max_bytes):
        break
    else:
        line = fo.readline(max_bytes - bytes_read)
        bytes_read += len(line)

如果你有一個文件:

f = open("a.txt", "r")
f.readline(size)

size 參數告訴要讀取的最大字節數

這會檢查沒有換行符的數據:

f=open('abc.txt','r')
dodgy=False
if '\n' not in f.read(1024):
    print "Dodgy file - No linefeeds in the first Kb"
    dodgy=True
f.seek(0)
if dodgy==False: #read the first 100 lines
    for x in range(1,101):
        try: line = next(f)
        except Exception as e: break
        print('{0}: {1}'.format(x, line))
else: #read the first n bytes
    line = f.read(1024)
    print('bytes: '+line)
f.close()

暫無
暫無

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

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