この記事では、Pythonでファイルの行をスキップする方法を説明します。これを行うには複数の方法があります。この投稿では、2つのアプローチについて説明します。
1. readlines()メソッドを使用する
ザ readlines() メソッドはファイルを読み取り、リストを返します。ここで、リストの各項目にはファイルの行が含まれています。つまり、list [0]には最初の行があり、list[1]には2番目の行があります。
リストなので、繰り返し処理できます。現在の行番号がスキップしたい行番号と等しい場合、その行を省略します。それ以外の場合は、それを考慮します。
スキップしたい行を除いて、すべての行を印刷する次の例を考えてみます。
def skipLine(f, skip): lines = f.readlines() skip = skip - 1 #index of the list starts from 0 for line_no, line in enumerate(lines): if line_no==skip: pass else: print(line, end="")
リトル・マーメイドのケースカバー
上記のコードを、の最初の行をスキップして試してみましょう。 sample.txt ファイル。
sample.txt
This is a sample file. Python is a very powerful programming language. Let's see how to skip a line in Python. It is very easy. I love Python. It makes everything so fun.
try: f = open("sample.txt", "r") skipLine(f, 1) finally: f.close()
出力
Python is a very powerful programming language. Let's see how to skip a line in Python. It is very easy. I love Python. It makes everything so fun.
3つスキップしましょう rd ライン。
try: f = open("sample.txt", "r") skipLine(f, 3) finally: f.close()
出力
This is a sample file. Python is a very powerful programming language. It is very easy. I love Python. It makes everything so fun.
行の総数よりも大きい、または1未満の値を渡した場合、何も起こりません。
2. readlines()メソッドとリストスライシングを使用する
以来 readlines() メソッドはリストを返します。特定の行をスキップするためにスライスを実行できます。次の例を考えてみましょう。
def skipLineSlicing(f, skip): skip -= 1 #index of list starts from 0 if skip < 0: # if the skip is negative, then don't make any changes in the list skip= 1 lines = f.readlines() lines = lines[0:skip] + lines[skip+1:len(lines)] for line in lines: print(line, end="")
の最後の行をスキップしましょう sample.txt ファイル。
try: f = open("sample.txt", "r") skipLineSlicing(f, 5) finally: f.close()
出力
This is a sample file. Python is a very powerful programming language. Let's see how to skip a line in Python. It is very easy.