LoginSignup
0
3

More than 3 years have passed since last update.

Pythonでファイル操作

Last updated at Posted at 2020-03-29

初めに

Pythonでのファイル操作時に使う関数たち

ファイル一覧取得

python
import os
os.listdir('../') # 引数に文字列でPATHを渡す

ファイル、フォルダの存在確認

python
os.path.exists('../test.csv') # ファイル、フォルダの存在確認
os.path.isfile('../test.csv') # 対象がファイルかどうかの確認
os.path.isdir('../test') # 対象がフォルダかどうかの確認

ファイル、フォルダをrename

python
os.rename('../test.csv', '../test2.csv') # 引数は元のファイルPATH、変更後のファイルPATHの順

フォルダを作る

python
os.makedirs('../test') # 指定のPATHにフォルダを作る (すでにフォルダが存在している場合エラー)

コピー

ファイルをコピー

python
import shutil
shutil.copy2('../test.csv', '../test/test.csv') # 引数はコピー元、コピー先の順

フォルダをコピー

python
shutil.copytree('../test/', '../test2/') # 引数はコピー元フォルダ、コピー先フォルダの順

移動

ファイルを移動

python
shutil.move('../test.csv', '../test/test.csv') # 引数はコピー元フォルダ、コピー先の順

フォルダを移動

python
shutil.copytree('../test/', '../test2/') # 引数はコピー元フォルダ、コピー先フォルダの順
shutil.rmtree('../test/')

削除

ファイルを削除

python
os.remove('../test/test.csv')

フォルダを削除

python
shutil.rmtree('../test/')

読み込み

python

f = open('test.txt','r')

for row in f:
    print row.strip()

f.close()

# 又は

with open('test.txt','r') as f:
    for row in f:
        print row.strip()  # withを使用する場合はclose()が必要ない

書込み

python
f = open('test.txt','w')

f.write('hoge\n')

f.close()
0
3
0

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
3