shutil : 파일, 폴더와 관련된 함수와 클래스를 제공하는 라이브러리
os : 운영체제와 관련된 함수와 클래스를 제공하는 라이브러리

* listdir : 폴더의 파일 목록 조회
* makedirs : 폴더 생성
* isdir : 폴더가 이미 존재하는지 확인
* copyfile : 파일 복사

from os import listdir, makedirs
from os.path import isdir
from shutil import copyfile

input_dir = 'C:\\input\\'
output_dir = 'C:\\output\\'

file_list = listdir(input_dir)
for file in file_list :
    f_name = file[3:-4] + '.xlsx'
    if not isdir(output_dir) :
         makedirs(output_dir)
    copyfile(input_dir + f_name, output_dir + f_name)

위는 단순히, input_dir폴더에 있는 것을 output_dir폴더로 옮기는 것이다. 만약 특정 기준으로 폴더별로 옮기거나 , 파일명을 바꿀 수도 있다. 파일복사 참 쉬움...copyfile 끝.
* (폴더 복사) shutil.copytree : 원본 폴더가 파일이거나, 대상경로에 파일 또는 폴더가 존재할 경우 오류 발생
* (폴더 삭제) shutil.rmtree : 입력값이 파일인 경우 오류 발생
* (파일 삭제) shutil.unlink : 입력값이 폴더인 경우 오류 발생
ex) from shutil import copytree
copytree('c:\\input_dir' , 'c:\\output_dir')
rmtree('c:\\output_dir')
unlink('c:\\input_dir\\download.txt')
* (파일 삭제) shutil.unlink : 입력값이 폴더인 경우 오류 발생
* 파일열기 및 쓰기(CSV 파일 포함)
afile = open('test.csv' , 'w')
afile.write('년월,매출\n')
* 파일열기 및 읽기
ex) f = open(testfile , 'r')
while True :
row = f.readline()
if not row :
break


파이썬 엑셀다루기

* openpyxl 이용... (cmd 창에서 > 'pip install openpyxl' 로 설치)
회사 PC의 경우 파일 암호화 등으로 오류 발생이 가능하므로, try 문을 추가하여 트러블 슈팅에 참고...

from os import listdir
from openpyxl import load_workbook, Workbook

jobdir = "C:\\workspace\\org\\"
outdir = "C:\\workspace\\out\\"
files = listdir(jobdir)

files.sort(reverse=True)

result_xlsx = Workbook()
result_sheet = result_xlsx.active        #최근 활성화된 탭


try :
    for myfile in files :
        if myfile[-4:] != "xlsx" :                    # 폴더에서 엑셀파일이 아닌 경우 skip
            continue
        print(myfile)
        tg_xlsx = load_workbook(jobdir + myfile, read_only=True)
        tg_sheet = tg_xlsx["Sheet1"]
        
        for row in tg_sheet.iter_rows() :
            row_data = []
            for cell in row :
                row_data.append(cell.value)
            result_sheet.append(row_data)

     result_xlsx.save(outdir + "result.xlsx")
except Exception as e :
    print(e)
finally :
    print('end')

정말 단순

#특정셀, 열, 행을 읽는 샘플 코드#


from openpyxl import load_workbook

xlsx = load_workbook('sample.xlsx', 'read_only=True) #read_only로 읽으면, 필요시마다 행간을 메모리로 읽어 속도 향상
sheet = xlsx.active

rows = sheet['1:2']           # 1~2행 읽기
rows = sheet['1']              # 첫 번째 행 가져옴
for row in rows :              # A1, B1, C1 읽기
col    = sheet['A']              # 첫 번째 열을 가져옴
for cell in col :                  # A1, A2, A3 읽기..

wb.close()                        # 닫기.

 

Posted by 목표를 가지고 달린다
,