ファイルを読み込んで、1行目だけをコンソールに出力するには readlines() を使う。
例
f = open("data.txt") lines = f.readlines() print(lines[0][:-1]) f.close()
読み込みファイル
data.txt の中身は
1 2 3 4 5 6 7 8 9
結果
1 2 3
雑記
投稿日:
ファイルを読み込んで、1行目だけをコンソールに出力するには readlines() を使う。
f = open("data.txt") lines = f.readlines() print(lines[0][:-1]) f.close()
data.txt の中身は
1 2 3 4 5 6 7 8 9
1 2 3
執筆者:seyanen
関連記事
data.txt からの入力から、「4 5 6」というデータがある行を削除して、output.txt に出力する。(データの各行の最後に \n があることに注意。) 例 f = open(‘data. …
色を1行ごとに交互につけるには、\xcolor パッケージを使った上で、\rowcolors コマンドを使って色を指定する。 例 \usepackage[table]{xcolor} \begin{d …
python3 でリストから重複を削除したリストを作成する方法
いったん dictionary に変換してから、新しいリストを作成する。すると、重複を除いたリストが作れる。 例 list1 = [‘1′,’2′,’3′,’1′,’2′,’5’] dict1 = d …
python3 で、文字列を一文字ずつのリストに変換する方法
string を list() で変換すれば良い。 例 str1 = ‘Good morning.’ list1 = list(str1) print(list1) 結果 [‘G’, ‘o’, ‘o’ …
2023/01/18
matplotlib のグラフ作成と gnuplot との対応 比較
2022/10/14
pythonで配列(リスト)の、ある要素がわかっているときにその次の要素を取得する方法。