[Python – 기초 강좌] 12. 파일(File) 다루기: 파일 읽기, 쓰기 등

Python에서 파일을 다루는 방법을 이해하는 것은 다양한 응용 프로그램을 개발하는 데 매우 중요합니다.

이 글에서는 파이썬에서 파일을 다루는 기본적인 방법과 그 필요성, 그리고 실제 예제를 통해 Python에서 파일을 어떻게 다루는지 자세히 설명하도록 하겠습니다.

Python에서 파일(File) 처리가 필요한 이유

파일 처리(File Handling)는 데이터를 저장(Store)하고, 수정(Modify)하고, 읽는(Read) 등의 작업을 수행할 수 있게 해줍니다.

이는 데이터 분석, 웹 개발, 자동화 스크립트, 로그 관리 등 다양한 분야에서 필수적입니다.

파일을 통해 프로그램이 실행될 때마다 데이터를 유지하고, 외부 데이터를 읽어 들여서 프로그램의 입력으로 사용할 수 있습니다.

File-handling

파일 다루기

파일 열기

Python에서 파일을 다루기 시작하려면 먼저 open() 함수를 사용하여 파일 객체를 생성해야 합니다.

open() 함수는 파일명과 함께 파일을 여는 모드를 지정하는 인자를 받습니다.

파일을 open() 했으면 close()를 통해 자원 누수(Resource Leak)이 발생되지 않도록 해주어야 합니다.

예제

file = open('assets/example.txt', 'r')  # Open file in read mode
file = open('assets/example.txt', 'w')  # Open file in write mode
file = open('assets/example.txt', 'a')  # Open file in append mode
file = open('assets/example.txt', 'r+') # Open file in read and write mode

file.close() # Close file 

파일 읽기

파일 객체가 생성되면, 다음과 같은 방법으로 파일 내용을 읽을 수 있습니다.

  • read() 메소드는 파일의 전체 내용을 문자열로 반환합니다.
  • readline() 메소드는 파일의 다음 한 줄을 문자열로 반환합니다.
  • readlines() 메소드는 파일의 모든 줄을 각각의 문자열로 가지는 리스트로 반환합니다.
전체 읽기 read()
file = open('assets/example.txt', 'r')
content = file.read()       # read the entire file
print(content)
한 줄 읽기 readline()
file = open('assets/example.txt', 'r')
first_line = file.readline() # read the first line
print(first_line)
모든 줄을 리스트로 읽기 readlines()
file = open('assets/example.txt', 'r')
all_lines = file.readlines() # read all lines
print(all_lines)

파일 쓰기

파일에 데이터를 쓰려면 파일을 쓰기(‘w’) 또는 추가(‘a’) 모드로 열어야 합니다.

write() 메소드를 사용하여 파일에 내용을 쓸 수 있습니다.

file = open('assets/write_sample.txt', 'w')
file.write("Hello, Python!\n")  # Write a string to a file
file.close()

맨 앞줄 혹은 맨 뒷줄에 추가하는 방법을 소개하겠습니다.

맨 뒷줄에 문자열 추가하기

파일의 맨 뒤에 문자열을 추가하는 것은 상대적으로 간단합니다.

파일을 추가 모드(‘a’)로 열고, 원하는 문자열을 write() 메서드를 사용해 추가할 수 있습니다.

def add_to_end(filename, string):
    with open(filename, 'a') as file:
        file.write(string + '\n')


# append string to last row
add_to_end('assets/write_sample.txt', 'This Line is appended in the end')
맨 앞줄에 문자열 추가하기

파일의 시작 부분에 문자열을 추가하려면, 파일의 전체 내용을 읽고, 수정한 후 다시 써야 합니다.

이는 메모리 사용량이 많을 수 있으므로 주의가 필요합니다.

def add_to_beginning(filename, string):
    with open(filename, 'r+') as file:
        # Store the current content of the file
        content = file.read()
        # Move the cursor to the start of the file
        file.seek(0)
        # Write the new string at the beginning
        file.write(string + '\n' + content)

# append string to first row
add_to_beginning('assets/write_sample.txt', 'This Line is appended in the beginning')

파일 자동 닫기 (with)

파일 작업을 할 때는 파일을 제대로 닫아 자원 누수를 방지해야 합니다.

with 구문을 사용하면 파일을 자동으로 닫을 수 있어 편리합니다.

with open('assets/example.txt', 'r') as file:
    content = file.read()
    print(content)

폴더 및 경로 다루기

상대 경로와 절대 경로

경로를 넣을 때 위치는 상대 경로와 절대 경로를 넣을 수 있습니다.

상대 경로란?

상대 경로는 현재 작업 중인 디렉토리에 대해 상대적인 파일 경로를 나타냅니다.

예를 들어, 현재 작업 중인 디렉토리가 /home/username/Documents이고, 그 안에 example.txt 파일이 있다면, 상대 경로는 단순히 example.txt가 됩니다.

하위 폴더에 있는 파일을 참조하려면 'subfolder/example.txt'와 같이 지정할 수 있습니다.

절대 경로란?

절대 경로는 시스템의 루트에서부터 전체 파일 경로를 나타냅니다.

예를 들어, 'C:/Users/Username/Documents/example.txt'와 같이 표현할 수 있습니다.

Python에서 경로를 다루는 모듈 (os)

Python에서 폴더 및 경로를 다루는 작업은 주로 os 모듈과 os.path 서브 모듈을 통해 수행됩니다.

이 모듈들은 파일 시스템을 탐색하고, 파일 및 디렉토리 경로를 조작하며, 파일의 메타데이터를 얻는 데 사용됩니다.

현재 작업 디렉토리 확인 및 변경

현재 작업 디렉토리를 얻거나 변경할 때는 os.getcwd()os.chdir() 함수를 사용합니다.

chdir() 사용시, 만약 해당 path가 존재하지 않으면 error가 발생됩니다.

# check current directory path
current_directory = os.getcwd()
print("Current directory path:", current_directory)

# Change directory path
os.chdir(current_directory + '/assets')
print("Changed directory path:", os.getcwd())

디렉토리 생성 및 삭제

새로운 디렉토리를 만들거나 기존 디렉토리를 삭제할 때는 os.mkdir()os.rmdir() 함수를 사용합니다.

os.makedirs() 함수는 중간 디렉토리가 없어도 모든 중간 디렉토리를 생성할 수 있습니다.

생성
# Create a new directory
os.mkdir('new_directory')

# Create a new directory with sub-directory
os.makedirs('new_directory/sub_directory')
삭제

단, 삭제를 진행할 때는 폴더는 비어져 있어야 합니다.

# Delete a directory (only works for empty directory)
os.rmdir('new_directory/sub_directory')
os.rmdir('new_directory')

파일 및 디렉토리 존재 여부 확인

파일이나 디렉토리의 존재 여부를 확인할 때는 os.path.exists() 함수를 사용합니다.

특정 경로가 파일인지 디렉토리인지 확인하려면 os.path.isfile()os.path.isdir()를 사용합니다.

파일 / 폴더가 존재하는지 확인
# Check File / Diectory Exist
print("Check File Exist:", os.path.exists('assets/example.txt'))
print("Check Directory Exist:", os.path.exists('new_directory'))
파일인지 폴더인지 확인
# Check File / Directory
print("If File:", os.path.isfile('assets/example.txt'))
print("If Directory:", os.path.isdir('new_directory'))

파일 및 디렉토리 목록 가져오기

특정 디렉토리 내의 파일 및 하위 디렉토리 목록을 얻으려면 os.listdir() 함수를 사용합니다.

# Get File / Directory List
entries = os.listdir('.')
print("Current Directory Contents List:", entries)

참고 문헌

Leave a Comment

Discover more from Devitworld

Subscribe now to keep reading and get access to the full archive.

Continue reading