##
# -*- coding: utf-8 -*-
"""
file path 를 설정하여
directory path 가 없으면 os.makedirs 를 이용해서 directory 를 만들어주고
os.utime() 으로 file 을 새로 만든다.
"""
import os
def mkdir_if_not(filepath):
"""
path 의 directory path 부분이 없으면 mkdir 을 한다.
:param filepath: 파일 패쓰
:return: filpath 그대로 리턴
"""
# os.path.split(filepath)
# directory path 와 file name 으로 나누어 return
dirpath, filename = os.path.split(filepath)
print 'Directory Path : ', dirpath
print 'File Name : ', filename
if not dirpath:
return filepath
if not os.path.exists(dirpath):
os.makedirs(dirpath)
return dirpath, filename
def touch(fname, times=None):
# os.utime(path, times)
# Parameters
# path -- This is the path of the file.
# times -- This is the file access and modified time. If times is none,
# then the file access and modified times are set to the current time.
# The parameter times consists of row in the form of (atime, mtime)
# i.e (accesstime, modifiedtime).
fhandle = open(fname, 'a')
try:
# os.utime() 이용해서 linux 에서 touch 하듯 make file.
os.utime(fname, times)
finally:
fhandle.close()
def test():
filepath = '/data/temp/tempfile.txt'
dirpath, filename = mkdir_if_not(filepath)
print 'Directory Path : ', dirpath
print 'File Name : ', filename
touch(filepath)
# p.s.
# os.utime() 사용법
import time
a = time.time() # a : accesstime
b = time.time() + 120 # b : modified time, 120초(2분) 더해줌.
os.utime(filepath, (a, b)) # (a, b) :
if __name__ == '__main__':
test()