0
0

More than 1 year has passed since last update.

【Python3】テキストファイルの内容を取得する方法

Last updated at Posted at 2021-12-16

はじめに

今回はPythonからテキストファイルの内容を取得し、変数に代入する方法を紹介します。

動作環境

Python 3.10.0

Mac OS Monterey

準備

まず、このような感じのファイルを作ります。

test(フォルダー)
main.py
text.txt

今回はtext.txtの内容を取得するプログラムを作っていきたいと思います。

本編

ファイルの読み込み

open = open("text.txt", "r")

"r"は読み込み(read)を表しています。

変数に代入

data = file_open.read()

ファイルを閉じる

open.close()

この三つを組み合わせることでテキストファイルの内容を取得することができます。
以下、サンプルコード。

file_read.py
# Coding : utf-8

# ファイルの読み込み
open = open("test_text.txt", "r")

# 変数に代入
data = open.read()

# ファイルを閉じる
open.close()

# 出力
print(data)

ファイルの内容が出力されます。
ちなみに予めテキストファイルに文字列を代入しておく必要があります。

さいごに

書き込みの方法も別記事でまとめています↓
https://qiita.com/Matcha_5428/items/e5523b518cd970ce9510

訂正などあればコメントからお願いします。

0
0
2

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
0
0