3
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Python ファイル読み書き〜osモジュール

Last updated at Posted at 2019-03-09

やること

よく使いたくなるが、細かい事は忘れがちなので、
osモジュール系、ファイル読み書き系を備忘録として。

環境

virtualbox 5.2.26
vagrant 2.1.2
python 3.5.2
mac 10.14.2

ファイル読み込み

※読み込みはopenのモード省略可

ファイル全体を文字列として読み込み read()

input.py

with open('test.txt', encoding='utf-8') as f:
  contents = f.read()
  print(contents.rstrip())

output.py
huhu
haha
yeah

ファイル全体をリストとして読み込み readlines()

input.py
with open('test.txt', encoding='utf-8') as f:
  contents = f.readlines()
  print(contents)

output.py
['huhu\n','haha\n','yeah\n']

ファイルを一行ずつ読み込み readline()

input.py
with open('test.txt', encoding='utf-8') as f:
  contents = f.readline()
  print(contents.rstrip())

  contents = f.readline()
  print(contents.rstrip())

  contents = f.readline()
  print(contents.rstrip())

# 読み込む度一行ずつ進んでいく。

output.py
huhu
haha
yeah

forで読み込む

input.py
with open('test.txt', encoding='utf-8') as f:
  for row in f:
    print(row.rstrip())

output.py
huhu
haha
yeah

ファイル書き込み

上書き mode='w'

input.py
with open('test.txt', 'w', encoding='utf-8') as f:
  f.write('''yeah
haha
huhu
''')

test.txt
yeah
haha
huhu

末尾に追加書き込み mode='a'

input.py
with open('test.py', 'a', encoding='utf-8') as f:
  f.write('hello')

test.txt
yeah
haha
huhu
hello

先頭、途中に書き込みする mode='r+'

input.py
with open('text.txt', encoding='utf-8') as f:
  l = f.readlines()
  l.insert(0, 'huhahahaha\n')

# insert(PLACE, VALUE)

with open('text.txt', 'r+', encoding='utf-8') as f:
  f.writelines(l)

# writelines = シーケンス型を書き込む
test.py
huhahahaha
yeah
haha
huhu
hello

OSモジュール

os.path()

os.path.exists()

指定フォルダにファイルが存在するか確認する

input.py
import os


def search(target, file_name):
  path = os.path.join(target, file_name)
  # os.path.joinはos関係なくパスを連結してくれる。
  
  if os.path.exists(path):
    print(path + ' は存在するらしい')
  else:
    print(path + ' は存在しない?')

if __name__ == '__main__':
  search('宇宙', '生命体')
  search('test', 'test.py')

output
宇宙/生命体 は存在しない
test/test.py は存在するらしい

os.path.isfile() , os.path.isdir()

指定ファイル、指定ディレクトリがファイルかディレクトリか判別

input.py
import os 


def whatIsThis(target, file_name):
  path = os.path.join(target, file_name)

  if os.path.isfile(path):
    print(path + ' はファイルです。')

  if os.path.isdir(path):
    print(path + ' はディレクトリです。')

if __name__ == '__main__':
  whatIsThis(test, t.txt)
  whatIsThis(test, t)

output
test/t.txt はファイルです
test/t はディレクトリです

os.listdir()

指定ディレクトリ内のファイルやディレクトリのリストを返す

input.py
import os


def dir_list(target):
  for name in os.listdir(target):
    print(name)

if __name__ == '__main__':
  dir_list('.')

output
input.py
test

os.walk()

指定ディレクトリ内の子ディレクトリまで全てリストで返す

input.py
import os


# 子ディレクトリ内のファイルも全て連結して表示
def file_all(target):
  for root, dirs, files in os.walk(target):
    for file in files:
      path = os.path.join(root, file)
      print(path)

if __name__ == '__main__':
  dir_all('.')

output
./input.py
./test/test.txt
3
11
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
3
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?