파이썬의 가장 큰 특징이 자동화 기능이고,

그 중에서 특정 디렉토리나, 그 하위 디렉토리에 있는 모든 파일이나 특정 포멧의 확장자인 파일들을 열어서 

검색 한다든지,  특정 단어나 문장을 바꾼다든지(사실은 내용을 바꾼후 새로만듬) 등의 처리를 쉽게 할 수 있다.

Text 파일이나, Excel 파일 정도는 가능한것으로 알고 있다.

 

  • Text 파일 생성
  print('current dir:', os.getcwd()) # 현재 디렉토리 확인
  myfile = open('mytest.txt', 'w')
  myfile.write('Hello world')
  myfile.close()

mytest.txt 파일을 생성하고, 'Hello world' 라는 글을 쓴 후, 파일을 닫는 간단한 예제 이다.

만약 현재 디렉토리에 mytext.txt 파일이 존재 한다면, 덮어 씌워진다.

 

  • 경로 설정
import os

mypath = os.path.join('C:\\', 'dev', 'javasample') # 베이스 폴더 설정 (윈도우), 
print('windows path1:', mypath)	# 'C:\dev\javasample'
mypath = 'C:\\dev\\javasample'  
# mypath = 'C:/dev/javasample'  # 바로 위에 라인과 동일한 내용이다.
print('windows path2:', mypath)	# 'C:\dev\javasample'

mypath2 = os.path.join('usr', 'bin', 'spam')  # 베이스 폴더 설정 (리눅스)
print('linux path1:', mypath2)	# 'usr\bin\spam'
mypath2 = 'usr\\bin\\spam'   
print('linux path2:', mypath2)  # 'usr\bin\spam'

curpath = os.getcwd() # 현재 디렉토리 확인
print('current dir:', curpath)

경로 설정하는건 윈도우나 리눅스가 좀 차이가 있지만, 가능하면 os.path.join() 을 이용하여 경로를 생성하는것이 좋다.

참고로 'C:\\dev\\javasample'  대신에 'C:/dev/javasample'  이렇게 사용 가능하다.

 

  • 파일 삭제
import os

mypath = os.path.join('C:\\', 'dev', 'javasample', 'text.txt')
os.remove(mypath) # os.unlink(mypath) 와 동일, 파일 삭제

파일 삭제는 os.remove('파일경로')나 os.unlink('파일경로')를 사용하면 된다.

만약 파일 경로가 아니라 폴더 경로 이거나, 파일이 없거나, 권한이 없으면 예외가 발생된다.

 

  • 파일 생성, 추가, 읽기
# 파일 생성 또는 열기, 읽기
myfile = open('mytest.py', 'w')	# 'w' : 쓰기(파일이 없으면 생성, 있으면 덮어쓴다.), 'r' : 읽기, 'a' : 추가  
myfile.write('Hello world')
myfile.close()
myfile = open('mytest.py', 'r')
myfile.read()
myfile.close()

# 파일 읽기 (1 라인만 읽기)
f = open('foo.txt', 'r')
line = f.readline()	# 1라인만 읽기
f.close()

# 모든 내용 읽기 (파일 내용이 적을경우)
f = open('foo.txt', 'r')
lines = f.readlines()	
for line in lines:
	print(line)
f.close() 

# 모든 내용 읽기 (파일 내용이 많을 경우)
f = open('foo.txt', 'r')
while True:
    line = f.readline()
    if not line:
      break
    print(line)
f.close()
  
# 파일 자동으로 닫기(f.close()를 사용안해도 됨)
with open('foo.txt', 'r') as f
	f.write('test line added')

 

  • 파일 삭제 (예외 처리)
import os

try:
	mypath = os.path.join('C:\\', 'dev', 'javasample', 'text.txt')
	os.remove(mypath) # os.unlink(mypath) 와 동일, 파일 삭제
except OSError as e:
    print(f"Error:{e.strerror}")

 

  • 디렉터리 삭제
import os
import shutil

path = os.path.join('C:\\', 'dev', 'javasample', 'temp')

os.rmdir(path) # 빈 디렉토리 인 경우 삭제

shutil.rmtree(path) # 파일이 있는 디렉토리 인 경우 삭제

 

  • 안전삭제 (파일 및 디렉터리를 휴지통으로 보낸다.)
import send2trash

# test.txt 파일 생성
f = open('test.txt', 'a') # creates the file
f.write('aaaaa abbbb')
f.close()

send2trash.send2trash('test.txt') # test.txt 파일 휴지통으로 이동

 

  • 파일 pickle 모듈 (파일을 데이터 저장소 형식으로 사용, 바이너리 형태로 객체를 저장하고, 불러온다, object serialization)
import pickle
# 저장하기
colors = ['red', 'green', 'black']
f = open('colors.pickle', 'wb')	# 'wb' : 바이너리 형태로 쓰기
pickle.dump(colors, f)
f.close()

# 불러오기
f = open('colors.pickle', 'rb')	# 'rb' : 바이너리 형태로 읽기
colors = pickle.load(f)
print(colors)
f.close()

 

  • shutil 모듈 (파일이나 디렉터리를 복사, 이동, 리네임, 삭제를 수행하는 모듈)
import shutil, os

os.chdir('C:\\') # 이동
shutil.copy('C:\\test.txt', 'C:\\temp')  # C:\\temp\\test.txt 로 복사
shutil.copy('abc.txt', 'C:\\temp\\rename.txt') # C:\\temp\\rename.txt 로 이름을 바꾸어 복사 

shutil.move('C:\\test.txt', 'C:\\temp')  # C:\\temp\\test.txt 로 이동
shutil.move('abc.txt', 'C:\\temp\\rename.txt') # C:\\temp\\rename.txt 로 이름을 바꾸어 이동

shutil.rmtree('C:\\test.txt') # C:\\test.txt 파일 삭제
shutil.rmtree('C:\\temp\\temp2') # C:\\temp\\temp2 폴더 삭제

'C:\\temp\\rename.txt' 대신에 'C:/temp/rename.txt' 이렇게 사용해도 된다. 동일한 내용이다.

 

  • 디렉터리
import os

mydir = os.getcwd() # 현재 작업디렉터리를 보여줌
print(mydir)

os.chdir('c:\\temp\\test')	# 디렉터리 변경 
print(os.getcwd())

mypath = 'C:\\temp\\test\\mytest.py'
mybase = os.path.basename(mypath)	# mytest.py  파일명
print(mybase)
mydir = os.path.dirname(mypath)	# C:\\temp\\test  디렉터리명
print(mydir)

 

  • 디렉터리 순회 ( os.walk(path))
import os

# 지정 디렉터리 하위의 모든 디렉터리, 파일 출력
# os.walk('.') : 현제 디렉터리

for folder_name, subfolders, filenames in os.walk('C:\\dev'):
    print('현재 디렉토리: '+ folder_name)
    for subfolder in subfolders:
        print(folder_name +'의 하위 폴더 :' + subfolder)
    for filename in filenames:
        print(folder_name + '에 있는 파일 :' + filename)
    print(' ')

 

  • 파일 찾기 (glob.glob)
import glob

mylist = glob.glob('*') # 현재 디렉터리의 모든 파일을 리스트로 반환
print(mylist)
mylist = glob.glob('*.py') # py 파일을 리스트로 반환
print(mylist)

 

  • 특정한 폴더 하위의 모든 디렉터리, 파일을 검색하여, java확장자인 경우, 파일을 열어서 찾고자 하는 문자열이 있으면, 특정 문자열로 바꾸는 예제

https://replit.com/@dhshin38/Tutorial-Python#log4jchange.py

 

Tutorial Python

A Python repl by dhshin38

replit.com

 

 

'Python' 카테고리의 다른 글

Python 예외 처리  (0) 2022.01.23
Python zip파일 압축 및 해제  (0) 2022.01.23
Python 정규식  (0) 2022.01.15
Python list, tuple, dictionary, 리스트, 튜플, 딕셔너리  (0) 2022.01.15
Python 날짜, 스케쥴, process  (0) 2022.01.15

+ Recent posts