「Python」readline関数でファイルの1行読み込み文字列を返す

環境
PyCharm 2021.3.3
Python 3.9.2

書式
変数名 = open(ファイルパス名,’r’,encoding=’utf-8′)
変数名.readline()
readlineメソッドを利用して、1行読み込み文字列を返します。

使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
# coding: utf-8
str = "C:\\python\\test001.txt"
#ファイルを読み込む
fileres = open(str,'r',encoding='utf-8')
#1行読み込み
fA = fileres.readline()
fB = fileres.readline()
fC = fileres.readline()
fileres.close()
# 1行目の文字列が表示される
print (fA)
print (fB)
print (fC)
# coding: utf-8 str = "C:\\python\\test001.txt" #ファイルを読み込む fileres = open(str,'r',encoding='utf-8') #1行読み込み fA = fileres.readline() fB = fileres.readline() fC = fileres.readline() fileres.close() # 1行目の文字列が表示される print (fA) print (fB) print (fC)
# coding: utf-8

str = "C:\\python\\test001.txt"
#ファイルを読み込む
fileres = open(str,'r',encoding='utf-8')

#1行読み込み
fA = fileres.readline()
fB = fileres.readline()
fC = fileres.readline()

fileres.close()
# 1行目の文字列が表示される
print (fA)
print (fB)
print (fC)

実行結果

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
AAA
1222
32sd
AAA 1222 32sd
AAA

1222

32sd

 

Python

Posted by arkgame