5
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Pythonでテキストファイルの行数を取得する方法

Last updated at Posted at 2021-01-22

#Pythonでテキストファイルの行数を取得
import subprocess
cmd = "wc -l [テキストファイル名]"
c = subprocess.check_output(cmd.split()).decode().split()[0]
print(c)
#行数990002のファイルにかかった時間
0.05637836456298828 (sec)
他に以下でも取得できる

print(len(open('[テキストファイル名]').readlines()))  
#行数990002のファイルにかかった時間
0.2346503734588623 (sec)

print(sum(1 for line in open('[テキストファイル名]')))  
#行数990002のファイルにかかった時間
0.1792283058166504 (sec)

 それぞれかかる時間を比較すると、一番上の方法が最も速いが、何度も取得する必要がなければ大差は無い。

5
1
1

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
5
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?