LoginSignup
2
4

More than 5 years have passed since last update.

Pythonでのファイル読み込み

Last updated at Posted at 2017-11-30

最近Pythonで外部ファイルを読み込むことが増えており、
この記事を書こうと思いました。

外部ファイルを読み込む場合、基本的に渡されるテキストはひとまとまりになった物です。
なので、こうしてやると別々に配列に格納する事が出います。

file_read.py
hogeio = open("hoge.txt")
reader = hogeio.read()
hogeio.close()
reader = reader.split("\n")

見たらわかると思いますが、一応説明。
1行目で、ファイルをOPENし、2行目でリードします。
3行目で、クローズし、4行目で、Split("\n")で分割を行っております。
この4行目で、配列化することによって、改行された文字列の様に扱えます。

呼び出すときは、

get.py
for read_txt in hogeio :
    return read_txt

で受け取ることが出来ます。

そして、終端から受け取りたい場合もあると思いますので、そのサンプルコードも。

endpoint.py
arr_len = len(reader)
for i in range(arr_len) :
    print("{0}".format(reader[arr_len - i]))
2
4
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
2
4