taking everything from the module without objects starting __
1 2
from mymath import * print area(5)
import module’s name as another module name
another name is used for calling the module
It is recommended when the original name is too long or already used
1 2 3 4
import string as chstr print chstr print print chstr.punctuation
from module’s name import original name as another name[, name2 as another name2]
another name is used for calling the module
1 2 3 4 5 6
from string import replace as substitute[, upper as up] print substitute print substitute('ham chicken spam', 'chicke', 'egg')
print up print up('abc')
import can be used anywhere(including in a function)
Compile and Load time
import mymath works like this
Finding mymath.pyc
If that doesn’t exist, Finding mymath.py and creating mymath.pyc
Loading mymath.pyc into memory and executing
.pyc file
Byte code file
Kind of Object code not depending on machines or platform(OS)
Python takes both executing ways of compile language and interpreter language
Deciding about creating new .pycfile
When modificatin time of .py is more recently than modification time of .pyc
Without .pyfile, import is available with .pyc
It can be use as the way to hide the original code
Using the same name again
Though the name’s target is changed, the module remains in memory, if we import the module, that takes the module existing in memory. So, we can use the thing we defined additionally in the module at the code
Executing module and test code
__name__
It is usually used for knowing if this module is used as the root module or in other module by import
print os.listdir('.') # file list of present directory print
print os.listdir('../') # file list of parent directory
Recognizing file’s category
os.pathmodule recognizes and returns True or False
1 2 3 4 5 6 7 8 9 10 11 12 13
import os deffiletype(fpath): print fpath, ":", if os.path.isfile(fpath): print'Regular file' if os.path.isdir(fpath): print'Directory' if os.path.islink(fpath): print'Symbolic link'
flist = os.listdir('.') for fname in flist: filetype(fname)
Permission about file
Learning permission about file
os.access(filepath, mode)
the values we can put for mode
os.F_OK: testing if the file exists
os.R_OK: testing about reading permission
os.W_OK: testing about writing permission
os.X_OK: testing about opening or executing permission
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
import os deffileaccess(fpath): print fpath, ':', if os.access(fpath, os.F_OK): print'Exists', else: return if os.access(fpath, os.R_OK): print'R', if os.access(fpath, os.W_OK): print'W', if os.access(fpath, os.X_OK): print'X', print
flist = os.listdir('.') for fname in flist: fileaccess(fname)
Chagning the Permission for the file
os.chmod(filepath, mode)
1 2
import os os.chmod('sample.txt', 0777)
Manipulating files
Chagning the name of the file
os.rename(old_filepath, new_filepath)
1 2 3 4 5
import os os.rename('t.txt', 't1.txt')
print os.access('t.txt', os.F_OK) # checking if the file exists print os.access('t1.txt', os.F_OK)
Moving the file
os.rename(oldfilepath, new_filepath)
1 2 3 4 5
import os os.rename('t.txt', 'example/t1.txt')
# checking if the file exists print os.access('example/t1.txt', os.F_OK)
Copying the file
shutilmodule is used
shutil.copyfile(src_filepath, dest_filepath)
1 2 3 4
import os import shutil shutil.copyfile('sample.txt', 'sample_new.txt') print os.access('sample_new.txt', os.F_OK)
Manipulating the path of the file
Changing relative path to absolute path
os.path.abspath - relative path
no matter the existance of the file, it changes the path to absolute path
1 2
import os print os.path.abspath('o.txt')
Checking if the file exists in the given path
os.path.exists(filepath)
Dividing path name
Dividing path and file’s name
1 2 3 4
f = '/Users/booski/git/python/t.txt'
print os.path.basename(f) # extracting only the file's name print os.path.dirname(f) # extracting the directory's name
Dividing path and file’s name by one line - basename and dirname are made in a tuple
1
print os.path.split(f)
Dividing drive’s name and file path in MS windows
1
print os.path.splitdrive(f)
Dividing extension - path and extension are made in a tuple
import os deffiletype(fpath): print fpath, ":", if os.path.isfile(fpath): print'Regular file' if os.path.isdir(fpath): print'Directory' if os.path.islink(fpath): print'Symbolic link'
flist = os.listdir('.') for fname in flist: filetype(fname)
파일의 허가권
파일의 허가권 알아보기
os.access(filepath, mode)
mode에 들어갈 값
os.F_OK: 파일 자체가 존재하는 것을 테스트
os.R_OK: 읽기 권한이 있는 것을 테스트
os.W_OK: 쓰기 권한이 있는 것을 테스트
os.X_OK: 실행 권한이 있는 것(또는 디렉토리인지)을 테스트
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
import os deffileaccess(fpath): print fpath, ':', if os.access(fpath, os.F_OK): print'Exists', else: return if os.access(fpath, os.R_OK): print'R', if os.access(fpath, os.W_OK): print'W', if os.access(fpath, os.X_OK): print'X', print
flist = os.listdir('.') for fname in flist: fileaccess(fname)
파일의 허가권 변경하기
os.chmod(filepath, mode)
1 2
import os os.chmod('sample.txt', 0777)
파일 조작하기
파일 이름 변경하기
os.rename(old_filepath, new_filepath)
1 2 3 4 5
import os os.rename('t.txt', 't1.txt')
print os.access('t.txt', os.F_OK) # 파일 존재 여부 확인 print os.access('t1.txt', os.F_OK)
파일 이동하기
os.rename(oldfilepath, new_filepath)
1 2 3 4 5
import os os.rename('t.txt', 'example/t1.txt')
# 파일 존재 여부 확인 print os.access('example/t1.txt', os.F_OK)
파일 복사하기
shutil모듈 활용
shutil.copyfile(src_filepath, dest_filepath)
1 2 3 4
import os import shutil shutil.copyfile('sample.txt', 'sample_new.txt') print os.access('sample_new.txt', os.F_OK)
mode can be set as the Second parameter of openbuilt-in function default value is read only(r)
r - read only - file object is created in read only, file pointer moves to the beginning of the file, Error occurs if the file doesn’t exists
w - write only - creating new file or creating new file object in write only after removing original file’s content, file pointer moves to the beginning of the file
a - addding content at the bottom - creating file object in write only or creating new file if the file doesn’t exist and then putting the file pointer to the end of the file
Binary file mode
rb
wb
ab
It is recommended to close the file object by close() immediately like f.close()
Using read() assigns whole content after reading everything
Reading file line by line
Using forloof statement
1 2 3 4 5 6
f = open('t.txt') i = 1 for line in f: print i, ":", line, i += 1 f.close()
readline() - from present file pointer to new line character = A line
1 2 3 4 5 6 7 8
f = open('t.txt') line = f.readline() i = 1 while line: print i, ":", line, line = f.readline() i += 1 f.close()
readlines() - Saving line by line in a list, memory is used inefficiently It works differently depending on each cases - for instatement: not reading everything, taking line by line
1 2 3 4 5 6 7 8 9 10 11
f = open('t.txt') print f.readlines() # returning a list
# file pointer moves to the beginning of the file f.seek(0)
i = 1 for line in f.readlines(): print i, ":", line, i += 1 f.close()
xreadlines() - memory inefficiency improved
1 2 3 4 5 6 7 8 9 10 11
f = open('t.txt') print f.xreadlines() # returning file object
# file pointer moves to the beginning of the file f.seek(0)
i = 1 for line in f.xreadlines(): print i, ":", line, i += 1 f.close()
f = open('t.txt','w') stdout = sys.stdout #표준 출력 저장 sys.stdout = f #파일 객체로 표준 출력 변경 print'Sample output' pirnt 'Good' print'Good' f.close() sys.stdout = stdout #표준 출력 복원