0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Pythonでダイアログボックスにてファイルを選択する

Posted at

ファイルサイズの大きなファイルの先頭30行だけ表示させたい

サイズの大きなデータファイルをExcelで読み込むには時間がかかりすぎる,あるいは読み込めない.このようなデータを扱う時には,先頭部分だけを表示して,ヘッダやデータの配列(並んでいる順番)を確認したい.

以下のようなPythonスクリプトを用いれば,任意の行までを瞬時に表示することができる.

show30_file.py
# -*- coding: utf-8 -*-
import csv
import tkinter as tk
from tkinter import filedialog

# ファイルダイアログボックスを表示してファイルを選択
file_path = filedialog.askopenfilename()

# 選択したファイル名を取得して変数filenameに格納
filename = file_path.split("/")[-1]

print(f"Selected file name is : " + filename)

# csvファイルの最初の30行を表示する
# with open(filename, 'r', encoding='utf-8') as csvfile:
    # csvreader = csv.reader(csvfile)
    # lines = [next(csvreader) for _ in range(30)]

# txtファイルの最初の30行を表示する
with open(filename, 'r', encoding='utf-8', errors='ignore') as file:
    for i in range(30):
        line = file.readline()
        if not line:
            break
        print(line.strip())

# エンコーディングの問題を確認する
for i, line in enumerate(lines):
    print(f'Line {i+1}: {line}')

<注意事項>
ファイル内に日本語が含まれるなら,スクリプトの1行目は,必須(文字化け対策のおまじない).

ASCIIフォーマットなら,csvの部分を任意の拡張子(txtやdatなど)に変更すればOk.

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?