qshinoの日記

Powershell関係と徒然なこと

ファイル操作 by python

read write

#coding:utf-8 
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() 

#coding:utf-8 
f = open('test.txt','w') 
f.write('hoge\n') 
f.close()

'a' とすると追記。

ディレクトリ作成

import os 

new_dir_path = 'data/temp/new-dir'
os.mkdir(new_dir_path)

# FileExistsError: [Errno 17] File exists: 'data/temp/new-dir/' 

new_dir_path_recursive = 'data/temp/new-dir2/new-sub-dir'
os.makedirs(new_dir_path_recursive) 

# os.makedirs(new_dir_path_recursive)
# FileExistsError: [Errno 17] File


os.makedirs(new_dir_path_recursive, exist_ok=True) 

削除

import os 

os.remove('test.txt')

import shutil 

shutil.rmtree('data')

存在確認

#coding:utf-8 
import os.path 

if os.path.exists('test.log'):
  print u"存在." 
else: 
  print u"非存在"

uniq dir and file

そこそこユニークなファイルを作る。

/opt/data/日付/時刻

import os
import shutil
from datetime import dayetime

def newfile(dir="/opt/data", prefix):
  dt = datetime.now.strftime( "%Y%m%d" )
  tt = datetime.now.strftime( "%H%M%S" )

  mdt=dir+"/"+dt

  os.mkdirs( mdt, exist_ok=True)

  name = mdt + "/"+ prefix + "-" + tt
  f = open( name, "w" )
  return f, name

f, name =newfile("myfile")
f.write( "hello" )
f.close()


# with構文

https://reiki4040.hatenablog.com/entry/20130331/1364723288