Python > 入出力・ファイル操作


画面出力

print()
 


改行を抑える

print(s, end="")

変数間の区切りを変える

何も指定しないと半角スペースが入るが、カンマ区切りなどに変えたいときは、sepを設定
print(s, sep=",")

ファイルパスの操作

import os.path
 
os.path.basename(path)  # ファイル名を返す
os.path.dirname(path)  # ディレクトリ名を返す
os.path.splitext(path)  # 拡張子(ext)とそれ以外(パス含む, root)に分ける。(root, ext)
 


Lecture 68 絶対パス、相対パス


Lecture 90 ファイルの作成

open でファイルオブジェクトをつくる
open - Python 3.6.5 ドキュメント
write で書き込む
close でファイルオブジェクトを解放する

文字コードは encoding= で指定


Lecture 91 with ステートメントでファイルをopenする

with open("test.csv","w",newline="", encoding='utf-8') as f:
   fieldnames = ["place","count"]
   writer = csv.DictWriter(f, fieldnames=fieldnames)
   # 書き込み
   writer.writeheader()
   for data in datas:
       writer.writerow(data)

with ブロックで、ファイルを閉じるところまで面倒を見る。

openメソッド

open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

  • mode
    • r:読み込み
    • w:書き込み
    • a:追記

Lecture 92 ファイルの読み込み

with open("text.txt","w") as f:
f.read()
f.readline()

Lecture 93 seekを作って移動する

f.seek(14) 読み込み位置を進める

Lecture 94 書き込み読み込みモード

with open("text.txt","w+") as f:
開いた瞬間に「さら」の状態で始まるので、書き込んであったものは消える
with open("text.txt","r+") as f:

Lecture 95 テンプレート

import string
string.Templete(s) でsをテンプレート化
$name で name に文字を入れられる

Lecture 96 csvファイルへの書き込みと読み込み

import csv
 
with open("test.csv","w") as csv_file:
    fieldnames = ["name", "count"] # 1行目に書き込むフィールド名
    writer = csv.DictWriter(f, fieldnames=fieldnames) # 書き込みファイルオブジェクトを作る
 
    # 書き込み
    writer.writeheader() # header の書き込み
    writer.writerow({"place":place,"count":1}) # データの書き込み
 
    writer = csv.DictWriter(...)
 


writerオブジェクトの生成

csv.writer(csvfile, dialect='excel', **fmtparams)
  • ユーザが与えたデータをデリミタで区切られた文字列に変換し、
  • ファイルオブジェクトに書き込むための writer オブジェクトを返す。

writerオブジェクト

行の書き込み

csvwriter.writerow(row)
row パラメータを現在の表現形式に基づいて書式化し、 writer のファイルオブジェクトに書き込みます。
writer オブジェクト - Python ドキュメント

Lecture 97 ファイルの操作

import os
os.path.exists(...)
os.path.isfile(...)
os.path.isdir(...)
os.rename(...)
os.symlink(...)
os.mkdir(...)
os.rmdir(...)
import pathlib
pathlib.Path( ).touch()
import glob
import shutil
shutil.rmtree(...)

Lecture 98 tarfileの圧縮展開
import tarfile
with tarfile.open("test.tar.gz","w:gz") as tr:
"r:gz"

Lecture 99 zipfileの圧縮展開
import zipfile
import test

Lecture 100 tempfile
import tempfile テンポラリファイルを作ってくれる
最終更新:2020年06月27日 16:12