毎日ちょっとPython ~ 24日目 ~

今日もファイルの読み書きよ

ファイルの読み書きの方法

プレーンテキストファイルを扱う場合のものになります。基本は、

1. open()関数を呼び出し、Fileオブジェクトを取得
2. Fileオブジェクトのread()やwerite()メソッドを呼び出して読み書きする
3. Fileオブジェクトのclose()オブジェクトを呼び出してファイルを閉じる

という手順を踏むことになります。

open()関数を用いてファイルを開く

open()関数を使ってファイルを開くには、開きたいファイルパスを文字列として渡します。絶対パスでも相対パスでも構わない。hello.txtにアクセスできるようにします。

 hello_file = open('D:\\Python\\ver5\\hello.txt')

open()を呼び出すと読み込みモードでファイルを開きます。この場合は読み込むだけが可能になり、ファイルに書き込んだり変更したりすることはできないです。

なのでPython上ではFileオブジェクトをhello_fileという変数に格納しただけです。このファイルを操作するには、このhello_fileに格納されたFileオブジェクトのメソッドを呼び出します。

ファイルの内容を読み込む

File全体を一つの文字列として読み込む場合は、Fileオブジェクトのread()メソッドを用います。

>>> hello_content = hello_file.read()
>>> hello_content
'hello world!\n'

※実は日本語を入れた形でやってみたんですけど、なんかエラー出ました。Decodeをどうするのかみたいなことを指定しないといけないかもしれないです。

>>> hello_content = hello_file.read()
Traceback (most recent call last):
 File "<pyshell#16>", line 1, in <module>
   hello_content = hello_file.read()
UnicodeDecodeError: 'cp932' codec can't decode byte 0xef in position 48: illegal multibyte sequence

readlines()というメソッドを用いれば、1行ずつの文字列のリストとしてファイルを読み込むこともできます。

>>> lore_file = open('D:\\Python\\ver5\\LoremIpsum.txt')
>>> lore_file.readlines()
['Lorem Ipsum is simply dummy text of the printing and typesetting industry.\n',
 "Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.\n",
 'It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.\n',
 ' It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.\n']

今日はここまで。

この記事が気に入ったらサポートをしてみませんか?