LoginSignup
0
0

Python学習10日目~ファイルの読み書き~

Posted at

テキストファイルの書き込み

# with open(ファイル名,'w',encoding='') as 変数:
with open('C:/Codes/Python/test01.txt', 'w', encoding='utf-8') as file:
    file.write('Python\n')  # ファイルオブジェクト.writeで書き込み
    file.write('Hello')

注意点

with open('C:\Codes\Python\test01.txt','w',encoding='utf-8') as file:
    file.write('Python\n') #ファイルオブジェクト.writeで書き込み
    file.write('Hello')
実行結果
Traceback (most recent call last):
  File "c:\Codes\Python\write.py", line 1, in <module>
    with open('C:\Codes\Python\test01.txt','w',encoding='utf-8') as file:
         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^      
OSError: [Errno 22] Invalid argument: 'C:\\Codes\\Python\test01.txt'

\はエスケープ文字として解釈され、'\t'はタブ文字と解釈されてしまっている
解決策として、以下のようにバックスラッシュを2つ重ねるか、正斜線'/'を使用してファイルパスを指定する

テキストファイルの読み込み

# with open(ファイル名,'r',encoding='') as 変数:
with open('C:/Codes/Python/test01.txt', 'r', encoding='utf-8') as file:
    print(file.read()) #ファイルオブジェクト.readで書き込み
実行結果
Python
Hello

テキストの内容を一行ずつ読み込んで表示させる

with open('C:/Codes/Python/test01.txt','w',encoding='utf-8') as file:
    file.write('Python\n') #ファイルオブジェクト.writeで書き込み
    file.write('Hello\n')
    file.write('GoodBye')

with open('C:/Codes/Python/test01.txt', 'r', encoding='utf-8') as file:
    for count,text in enumerate(file,1):
        print(count,text,end='')
実行結果
1 Python
2 Hello
3 GoodBye

CSVファイルの読み書き

書き込み

import csv
catalog = [('hat','3000'),('shirt','5000'),('shoes','4000')]
with open('C:/Codes/Python/catalog.csv','w',encoding='utf-8',newline='') as file:
    csv.writer(file).writerows(catalog)

writerowとwriterowsの違い

writerowは一行に書き込む、writerowsは複数行に書き込む

読み込み

with open('C:/Codes/Python/catalog.csv',encoding='utf-8') as file:
    for x in csv.reader(file):
        print(x)
実行結果
['hat', '3000']
['shirt', '5000']
['shoes', '4000']

JSONファイルの読み書き

書き込み

import json
catalog = [{'name':'hat','price':3000},
           {'name':'shirt','price':5000},
           {'name':'shoes','price':4000}]
with open('C:/Codes/Python/catalog.json','w',encoding='utf-8') as file:
    json.dump(catalog,file,indent=3)

dump関数はイテラブルの書き込みを行う
引数にindentを指定するとインデントを入れることができる

image.png

読み込み

with open('C:/Codes/Python/catalog.json',encoding='utf-8') as file:
    print(json.load(file))
実行結果
[{'name': 'hat', 'price': 3000}, {'name': 'shirt', 'price': 5000}, {'name': 'shoes', 'price': 4000}]
0
0
1

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