Python でファイルの最初の N 行を抽出する方法は?

Linda Hamilton
リリース: 2024-10-17 23:25:29
オリジナル
758 人が閲覧しました

How to Extract the First N Lines of a File in Python?

Retrieving the First N Lines of a File

Often, when working with large raw data files, it becomes necessary to extract a specific number of lines for further processing or analysis. In Python, there are multiple approaches to accomplish this task.

Reading First N Lines Using List Comprehension

A simple and effective method involves utilizing list comprehension:

<code class="python">with open(path_to_file) as input_file:
    head = [next(input_file) for _ in range(lines_number)]
print(head)</code>
ログイン後にコピー

This approach iterates through the input file using the next() function and stores the first lines_number lines in the head list.

Using the islice() Function

Another approach leverages Python's itertools module:

<code class="python">from itertools import islice

with open(path_to_file) as input_file:
    head = list(islice(input_file, lines_number))
print(head)</code>
ログイン後にコピー

Here, the islice() function is used to iterate over the first lines_number lines of the input file, creating a list of the extracted lines.

Effect of Operating System

The implementation described above should work regardless of the operating system being used. However, it's worth noting that in Python 2, the next() function is known as xrange(), which may require corresponding adjustments in older code bases.

以上がPython でファイルの最初の N 行を抽出する方法は?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

ソース:php
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
著者別の最新記事
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!