LoginSignup
45

More than 5 years have passed since last update.

【Python】改行コードの取り除く方法

Posted at

Pythonでテキストファイルを読み込んで、その内容を出力する際に、
改行コードで行と行の間に余分な空行が入ったことがあります。

  • 事象
test.txt
# 元のテキストファイル
Hello World.
Hello World.
Hello World.
test.py
fname = "test.txt"
with open(fname,"r") as file:
    for i in file:
        print(i)
#画面に出力結果
Hello World.

Hello World.

Hello World.

この改行コードを取り除く方法は以下にまとめます。

  • 検証:Python Version: 3.6.4
  • 方法1 rstrip
way1.py
with open(fname,"r") as file:
    for i in file:
        print(i.rstrip('\n'))
  • 方法2 replace
way2.py
with open(fname,"r") as file:
    for i in file:
        print(i.replace('\n',''))
  • 方法3 splitlines
way3.py
with open(fname,"r") as file:
    for i in file.read().splitlines():
        print(i)

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
45