파일 관련 기본들
디렉토리 이동, 생성, 삭제
파일의 생성, 쓰기, 삭제
import os
1. 파일 경로 만들기
os.path.join('usr', 'bin', 'spam')
filename = ['a', 'b', 'c']
os.path.join('c:\\Users\\Python', filename)
2. glob 모듈
glob.glob('*') : 현재 디렉토리의 모든 파일을 리스트로 반환
import glob
a = glob.glob('*.jpg')
for filename in glob.glob('*'):
print(filename)
3. 디렉토리
- 현재 작업 디렉토리 : os.getcwd()
- 디렉토리 변경 : os.chdir('c:\\windows\\systems')
4. base name, dir name
- full path에서 파일명 또는 마지막 경로 가져오기 : os.path.basename(path)
- full path에서 경로 가져오기 : os.path.dirname(path)
5. 파일 읽기와 쓰기
- 파일 쓰기
sales_log = open('filename.txt', 'w')
sales_log.write('wwww')
sales_log.close()
- 파일 읽기
sales_log = open('filename.txt', 'r')
print(sales_log.read())
sales_log.close()
1) readline - 1
f = open('new_file.txt', 'r')
line = f.readline()
print(line)
f.close()
2) readline - 2
f = open('new_file.txt', 'r')
while True:
line = f.readline()
if not line: break
print(line)
f.close()
3) readlines
f = open('new_file.txt', 'r')
lines = f.readlines()
for line in lines:
print(line)
f.close()
4) write
with open('foo.txt', 'w') as f:
f.write('Life is too short, you need python')
6. pickle (Object Serialization)
1) 저장
import pickle
colors = ['red', 'green', 'black']
f = open('colors.pickle', 'wb')
pickle.dump(colors, f)
f.close()
-------------------------------------
2) 로드
import pickle
colors = []
f = open('colors.pickle', 'rb')
colors = pickle.load(f)
f.close()
7. Shell Util
1) 파일 복사
import shutil, os
os.chdir('c:\\')
shutil.copy('c:\\src\\src.txt', 'c:\\dst')
shutil.copy('c:\\src\\src.txt', 'c:\\dst\\dst.txt')
2) 파일 이동 (원본파일 없어짐, 목적지에 파일이 존재하면 이동이 안됨)
import shutil
shutil.move('c:\\src\\src.txt', 'c:\\dst')
shutil.move('c:\\src\\src.txt', 'c:\\dst\\dst.txt')
3) 파일 삭제 : 복구 안됨
os.unlink(path) 또는 os.remove(path)
os.rmdir(path) : 해당 경로가 비어 있어야 함
shutil.rmtree(path) : 경로가 비어있지 않아도 모든 파일이 삭제됨
4) 파일 삭제 : 휴지통
pip install send2trash
import send2trash
send2trash.send2trash('c:\\src\\src.txt')
8. 디렉토리 순회 : os.walk(path), 하위의 하위 계속해서 끝까지 내려간다.
import os
for folder_name, subfolders, filenames in os.walk('c:\\src'):
print('Current folder : ', folder_name)
for subfolder in subfolders:
print('SUBFOLDER OF ', folder_name, ':', subfolder)
for filename in filenames:
print('FILE INSIDE ', folder_name, ':', filename)
print('')
9. zip파일
1) 압축 파일 정보
import zipfile, os
os.chdir('c:\\src\\')
exampleZip = zipfile.ZipFile('1.zip')
exampleZip.namelist() #zip 파일안의 파일 목록을 보여준다.
spamInfo = exampleZip.getinfo('test.cpp')
spamInfo.file_size #파일 크기를 보여준다.
spamInfo.compress_size # 압축 크기를 보여준다.
exampleZip.close()
2) 압축 해제
import zipfile, os
os.chdir('c:\\src\\')
exampleZip = zipfile.ZipFile('1.zip')
exampleZip.extractall()
exampleZip.close()
3) 압축 하기 : 압축 파일을 만들고 파일을 추가하는 방식이다
import zipfile, os
os.chdir('c:\\src\\')
newZip = zipfile.ZipFile('new.zip', 'w')
#압축 파일에 추가
newZip.write('main.cpp', compress_type=zipfile.ZIP_DEFLATED)
newZip.close()
#특정 폴더를 통째로 압축함수
def backup_to_zip(folder):
os.chdir(folder)
print('Current working directory is ' + os.getcwd())
#zip 파일명 생성
zip_filename = os.path.basename(folder)+'.zip'
print('Creating %s' % zip_filename)
if not os.path.isdir('..\\backup'):#폴더가 존재하지 않으면 생성
os.mkdir('..\\backup')
backupzip = zipfile.ZipFile('..\\backup\\'+zip_filename, 'w')
for foldername, subfolders, filenames in os.walk('.'):
#현재 폴더를 zip 파일에 추가
backupzip.write(foldername)
#하위 폴더를 zip 파일에 추가
for subfolder in subfolders:
print(os.path.join(foldername,subfolder))
backupzip.write(os.path.join(foldername,subfolder))
for filename in filenames:
if filename.endswith('.jpg'):
print('skip compressing file: ' + filename)
continue
backupzip.write(os.path.join(foldername,filename))
backupzip.close()
print('backup completed...')