TOP
class="layout-aside-left paging-number">
본문 바로가기
[파이썬 Projects]/<파이썬 기초>

[파이썬] 파이썬 기초 - 파일 복사, 디렉토리

by 기록자_Recordian 2025. 1. 21.
728x90
반응형
파일 복사하기

 

input으로 불러올 파일과 저장할 파일명을 받은 뒤,

불러온 파일의 내용을 저장할 파일에 그대로 복사할 수 있다.

# 파일 복사하기
infileName = input("입력 파일 이름: ")
outfileName = input("출력 파일 이름: ")

print(infileName)
print(outfileName)

# 입력과 출력을 위한 파일을 연다
infile = open("files/" + infileName, "r", encoding="utf-8")
outfile = open("files/" + outfileName, "w", encoding="utf-8")

line = infile.readline()
while line:
    outfile.write(line)
    line = infile.readline() # while문에서는 계속 반복될 수 있게 해줘야 한다

infile.close() # 다 읽고나면 닫음
outfile.close()

 

새파일.txt 내용

 

코드를 실행하고나면 '새파일_1.txt' 라는 파일이 생성되고, 해당 내용은 기존 파일 내용과 같다.

 


os 모듈과 디렉토리

 

먼저, os 모듈을 사용하기 위해 import

import os

 

◆ __file__: 현재 작성중인 파일을 의미

print('파일의 상대경로: ', os.path.realpath(__file__))
print('파일의 절대경로: ', os.path.abspath(__file__))
print('파일의 디렉토리: ', os.path.dirname(__file__))

 

◆ os.getcwd(): 현재 open된 폴더 의미

dir = os.getcwd()
print('현재 작업 디렉토리: ', dir)

 

◆ os.walk(): 현재 디렉토리의 하위 폴더와 파일을 모두 접근

for dirName, subDirList, fnames in os.walk(dir): # dir에 현재 디렉토리 담겨 있음
    print("디렉토리: ", dirName)
    print('하위 폴더: ', subDirList) # 리스트로 반환
    for subdir in subDirList:
        print("###", subdir) # 하위 폴더 한 개씩 출력
    # 폴더 내 파일 가져오기
    for fname in fnames:
        print(os.path.join(dirName, fname)) # join은 합하는 것

 

os.chdir() : 작업 디렉토리 변경 (change direcotry, cd)

print('변경전 디렉토리: ', os.getcwd())
subdir = 'files'
os.chdir(subdir)
print('변경된 디렉토리:', os.getcwd())

 

◆ os.listdir() : 지정한 디렉토리 내의 모든 파일 이름을 리스트로 반환

for filename in os.listdir():
    if filename.endswith(".txt"):
        print(filename)

 

- 현재 작업 폴더에서 경로 이동해보기.

- 디렉토리 내의 파일만 불러온 후, 파일 내용 중 "python"이라는 단어를 포함하는 파일만 출력하기

import os
print("1. 현재 작업 폴더: ", os.getcwd())

# 경로 이동하기
os.chdir('files')
print("2. 이동한 경로: ", os.getcwd())

# 상위 폴더로 이동하기
os.chdir("..")
print("3. 상위 폴더: ", os.getcwd())

# 디렉토리 내의 목록 가져오기 (폴더, 파일)
for filename in os.listdir():
    # print(filename) > 모든 목록
    if os.path.isfile(filename): # 파일인 경우에만 출력
        # print(filename)
        infile = open(filename, "r", encoding="utf-8")
        for line in infile:
            e = line.rstrip()
            if "python" in e:
                print("     ---- python 단어가 포함된 파일 : ", filename, ':', e)
        infile.close()


이미지 복사하기

 

아래와 같은 '123.png' 파일을 동일한 폴더 내에 복사하는 코드 (복사된 파일의 파일명은 '123copy.png')

infile = open('files/123.png', 'rb')
outfile = open('files/123copy.png', 'wb')

# 이미지 파일은 크기가 크므로 버퍼를 이용하여 읽음
while True:
    copy_buffer = infile.read(1024)
    if copy_buffer:
        outfile.write(copy_buffer)
    else:
        break

infile.close()
outfile.close()
print("이미지 복사 완료")

※ read(1024)를 하는 이유: 한번에 읽어들이는 데이터의 크기(1kb == 1024byte) 

 

코드를 실행하고 나면 files 라는 폴더 내에 복사된 이미지 파일이 생성된다.


pickle : 객체를 쓰고 읽는 모듈

 

pickle 모듈: 객체를 파일에 저장하는 모듈. 형식을 유지하면서 데이터를 저장하는 방법

  • dump: 쓰기
  • load: 읽기

아래와 같이 소리, 영상 품질, 무기 목록이라는 Key와 각 value가 들어있는 딕셔너리를 pickle 모듈을 이용해 딕셔너리 자체로 저장하고 불러오는 코드를 작성해 본다.

import pickle

gameOption = {
    "Sound" : 8,
    "VideoQuality" : "HIGH",
    "WeaponList" : ["gun", "missile", "knife"]
    }

# 딕셔너리 저장
file = open('files/gameOption.p', 'wb')
pickle.dump(gameOption, file)
file.close()

# 딕셔너리 불러오기
file = open('files/gameOption.p', 'rb')
loaded_dic = pickle.load(file)
print("불러온 딕셔너리:\n", loaded_dic)

  • 저장할 때에는 해당 딕셔너리를 저장할 경로와 쓰기모드(rb)를 입력 후, 해당 변수를 입력한 뒤
  • pickle.dump(딕셔너리명, 저장하는 변수명) 을 통해 딕셔너리(객체)를 저장한 후
  • 파일을 닫는다.
  • 해당 객체를 불러올 때에는 저장할 때와 비슷하나, 쓰기모드가 아닌 읽기모드(rb)를 입력 후,
  • pickle.load(파일을 불러오는 변수명)을 입력하면 된다.

아래와 같이 with 문을 써도 된다.

with open('files/gameOption.p', 'wb') as file:
    pickle.dump(gameOption, file)

with open('files/gameOption.p', 'rb') as f:
    object = pickle.load(f)
    print(type(object))
    print(object)
    for key, value in object.items():
        print(f"{key}:{value}")


다음 내용

 

[파이썬] 파이썬 기초 - 예외 처리 보완

예외 처리 이전 내용 [파이썬] 파이썬기초: 예외 처리(Exception Handling)시작에 앞서해당 내용은 ' 박응용 지음. 이지스 퍼블리싱' 을 토대로 작성되었습니다. 보다 자세한 내용은 해당 서적에 상세

puppy-foot-it.tistory.com

 

728x90
반응형