LoginSignup
14
16

More than 5 years have passed since last update.

Pythonファイル入出力についてのtips

Last updated at Posted at 2016-10-19

ファイル名の取得

全てのファイル名をpath付きで取得

カレントディレクトリ以下の全てのファイルを取得し、表示。

import os
import glob
rootpath='.'
for root, dirs, files in os.walk(rootpath):
    for file_ in files:
        file_path=os.path.join(root,file_)
        print file_path 

全てのファイル名をpathなし(ファイル名のみ)で取得

カレントディレクトリ以下の全てのファイルを取得し、表示。

import os
import glob
rootpath='.'
for root, dirs, files in os.walk(rootpath):
    for file_ in files:
        file_path=os.path.join(root,file_).split('/')[-1]
        print file_path

拡張子の選択

再帰的にカレントディレクトリ以下の全ての.tabファイルを取得し、表示。

import os
import glob
path='.'
for root, dirs, files in os.walk(path):
    for dir_ in dirs:
        dir_path=os.path.join(root,dir_)
        for table in glob.glob(dir_path+'/*.tab'):
            print table

ファイル名をつける

0で埋めてけたを揃える

>>> num=1
>>> "{0,04d}".format(num)
'0001'
>>> num=1
>>> "{0,4d}".format(num)
'   1'
>>> char='1'
>>> char.zfill(4)
'0001'

ファイル名から数字だけを抜き出す

>>> import re
>>> hoge='1257cfnewoaij2203'
>>> suuji=re.findall("(\d+)",hoge)
>>> print suuji
'1257' '2203'

ファイルの読み込み

列ごとに物理量が入っていると仮定。空白によって列が区切られている場合。

一般的IO

数字列と文字列が混在する場合

for line in open('test.tab', 'r'):
    itemList = line[:-1].split()
    print itemList

,で区切られている場合にはsplit(',')で、タブで区切られている場合にはsplit('/t')

Numpyによる読み込み

>>> import numpy as np
>>> data=np.loadtxt('input.txt').T

ファイルの書き込み

一般的IO

数字列と文字列が混在する場合

f=open('output.txt','w')
f.write(moji+'\n')
f.close()

Numpyによる書き込み

>>> np.savetxt('output.txt',data.T)
14
16
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
14
16