안녕하세요, 코딩하는곰입니다! 오늘은 파이썬에서 파일을 다루는 기본이자 핵심인 파일 입출력에 대해 깊이 있게 알아보겠습니다. 파일 읽기와 쓰기는 프로그래밍에서 가장 기본적이면서도 중요한 기능 중 하나인데요, 데이터 분석, 로그 기록, 설정 파일 관리 등 다양한 분야에서 필수적으로 사용됩니다. 이번 포스팅에서는 open(), read(), write() 함수를 중심으로 파이썬 파일 처리의 모든 것을 배워보겠습니다.
🎯 개발자 생산성 향상 방법을 찾고 있다면, (MySQL/MariaDB) ERROR 1216, 1217 해결법 외래 키(FK) 제약 조건으로 인한 삭제/수정 실패를 참고해보세요.
파이썬에서 파일을 다루기 위해서는 가장 먼저 open() 함수를 사용해야 합니다. open() 함수는 파일 객체를 생성하며, 파일을 읽거나 쓸 수 있는 인터페이스를 제공합니다.
file_object = open(file_path, mode='r', encoding=None)
| 모드 | 설명 |
|---|---|
| ‘r’ | 읽기 모드 (기본값) |
| ‘w’ | 쓰기 모드 (파일이 존재하면 내용 삭제) |
| ‘a’ | 추가 모드 (파일 끝에 내용 추가) |
| ‘x’ | 배타적 생성 모드 (파일이 존재하면 오류) |
| ‘b’ | 바이너리 모드 |
| ‘t’ | 텍스트 모드 (기본값) |
# 기본적인 파일 열기file = open('example.txt', 'r') # 읽기 모드file = open('example.txt', 'w') # 쓰기 모드file = open('example.txt', 'a') # 추가 모드# 바이너리 파일 열기binary_file = open('image.jpg', 'rb') # 바이너리 읽기 모드# 인코딩 지정하여 파일 열기korean_file = open('korean.txt', 'r', encoding='utf-8')
파일을 열 때 가장 중요한 것은 적절한 모드 선택과 인코딩 설정입니다. 특히 한글을 다룰 때는 encoding=‘utf-8’을 명시적으로 지정하는 것이 좋습니다.
일반적인 open() 사용 후에는 반드시 close()로 파일을 닫아야 하지만, with 문을 사용하면 자동으로 파일을 닫아줍니다.
# with 문을 사용한 파일 처리 (권장)with open('example.txt', 'r') as file:content = file.read()print(content)# 파일이 자동으로 닫힘# 여러 파일 동시에 처리with open('input.txt', 'r') as input_file, open('output.txt', 'w') as output_file:data = input_file.read()output_file.write(data)
with 문을 사용하면 예외 발생 시에도 파일이 안전하게 닫히므로, 메모리 누수를 방지하고 코드의 가독성을 높일 수 있습니다.
📘 코딩 튜토리얼과 가이드를 원한다면, (자바 기초) 클래스와 객체 개념 완벽 이해 - 인스턴스화와 메모리 구조까지를 참고해보세요.
파일에서 데이터를 읽어오는 방법은 여러 가지가 있습니다. 각 방법은 사용场景에 따라 장단점이 있으니 상황에 맞게 선택하는 것이 중요합니다.
# 파일 전체 내용 읽기with open('example.txt', 'r', encoding='utf-8') as file:content = file.read()print(content)# 지정한 크기만큼만 읽기with open('large_file.txt', 'r') as file:chunk = file.read(100) # 처음 100바이트 읽기print(chunk)
read() 함수는 파일의 전체 내용을 하나의 문자열로 반환합니다. 파일 크기가 클 경우 메모리 문제가 발생할 수 있으므로, 대용량 파일에서는 read(size) 형태로 조각씩 읽는 것이 좋습니다.
# 한 줄씩 읽기with open('example.txt', 'r', encoding='utf-8') as file:line = file.readline()while line:print(line.strip()) # strip()으로 줄바꿈 문자 제거line = file.readline()# 더 파이썬적인 방법with open('example.txt', 'r', encoding='utf-8') as file:for line in file:print(line.strip())
readline()은 파일에서 한 줄씩 읽어 문자열로 반환합니다. 파일 끝에 도달하면 빈 문자열을 반환합니다.
# 모든 줄을 리스트로 읽기with open('example.txt', 'r', encoding='utf-8') as file:lines = file.readlines()for line in lines:print(f"Line: {line.strip()}")# 리스트 컴프리헨션과 함께 사용with open('example.txt', 'r') as file:lines = [line.strip() for line in file.readlines()]print(lines)
readlines()는 파일의 모든 줄을 리스트 형태로 반환합니다. 작은 파일에서는 편리하지만, 큰 파일에서는 메모리를 많이 사용할 수 있습니다.
# CSV 파일 읽기 (간단한 버전)with open('data.csv', 'r') as file:header = file.readline().strip().split(',')for line in file:values = line.strip().split(',')print(dict(zip(header, values)))# 로그 파일에서 특정 패턴 찾기import rewith open('server.log', 'r') as file:for line_num, line in enumerate(file, 1):if re.search(r'ERROR', line):print(f"Error found at line {line_num}: {line.strip()}")# 대용량 파일 처리 (메모리 효율적)def process_large_file(filename):with open(filename, 'r') as file:for line in file:# 각 줄을 개별적으로 처리processed_line = line.strip().upper()yield processed_line# 제너레이터 사용for processed_line in process_large_file('big_data.txt'):print(processed_line)
닉네임을 고르다가 마음에 드는 걸 놓쳤다면? 생성 이력을 저장해주는 닉네임 추천 도구가 딱입니다.
파일에 데이터를 저장하는 방법도 다양합니다. 기본적인 쓰기부터 효율적인 대용량 데이터 처리까지 알아보겠습니다.
# 기본적인 파일 쓰기with open('output.txt', 'w', encoding='utf-8') as file:file.write('Hello, World!\n')file.write('파이썬 파일 입출력 연습중입니다.\n')# 여러 줄 쓰기lines = ['첫 번째 줄\n', '두 번째 줄\n', '세 번째 줄\n']with open('multi_line.txt', 'w') as file:for line in lines:file.write(line)# 포맷 문자열 활용name = '코딩하는곰'score = 95with open('result.txt', 'w') as file:file.write(f'이름: {name}\n')file.write(f'점수: {score}\n')file.write('합격!' if score >= 90 else '불합격!')
# 문자열 리스트를 파일에 쓰기data_lines = ["Python is powerful\n","File I/O is essential\n","Practice makes perfect\n"]with open('lines.txt', 'w') as file:file.writelines(data_lines)# 리스트 컴프리헨션과 함께 사용numbers = [1, 2, 3, 4, 5]number_lines = [f"Number: {num}\n" for num in numbers]with open('numbers.txt', 'w') as file:file.writelines(number_lines)
# 파일에 내용 추가하기with open('log.txt', 'a') as file:import datetimetimestamp = datetime.datetime.now()file.write(f'{timestamp}: 새로운 로그 항목\n')# 기존 파일 내용 유지하면서 추가def add_to_file(filename, content):with open(filename, 'a', encoding='utf-8') as file:file.write(content + '\n')# 파일 내용 수정 (특정 라인 변경)def modify_file_line(filename, line_number, new_content):with open(filename, 'r', encoding='utf-8') as file:lines = file.readlines()if 0 <= line_number < len(lines):lines[line_number] = new_content + '\n'with open(filename, 'w', encoding='utf-8') as file:file.writelines(lines)else:print("라인 번호가 유효하지 않습니다.")# 사용 예제modify_file_line('example.txt', 2, '이것은 수정된 내용입니다.')
class SimpleDataManager:def __init__(self, filename):self.filename = filenamedef add_record(self, name, age, city):with open(self.filename, 'a', encoding='utf-8') as file:file.write(f'{name},{age},{city}\n')def read_all_records(self):records = []with open(self.filename, 'r', encoding='utf-8') as file:for line in file:name, age, city = line.strip().split(',')records.append({'name': name,'age': int(age),'city': city})return recordsdef find_by_city(self, city):results = []with open(self.filename, 'r') as file:for line in file:name, age, record_city = line.strip().split(',')if record_city.lower() == city.lower():results.append({'name': name,'age': int(age),'city': record_city})return results# 사용 예제manager = SimpleDataManager('users.txt')manager.add_record('김철수', 25, '서울')manager.add_record('이영희', 30, '부산')print("모든 기록:")print(manager.read_all_records())print("\n서울에 사는 사람:")print(manager.find_by_city('서울'))
import osdef safe_file_operations():filename = 'important_data.txt'# 파일 존재 여부 확인if not os.path.exists(filename):print(f"{filename} 파일이 존재하지 않습니다.")returntry:with open(filename, 'r+', encoding='utf-8') as file:content = file.read()# 파일 처리 로직file.seek(0) # 파일 포인터를 처음으로 이동file.write("새로운 내용\n" + content)except PermissionError:print("파일 접근 권한이 없습니다.")except UnicodeDecodeError:print("파일 인코딩 문제가 발생했습니다.")except Exception as e:print(f"예 상치 못한 오류: {e}")# 디렉토리 생성과 함께 파일 저장def save_with_directory(data, filepath):directory = os.path.dirname(filepath)if directory and not os.path.exists(directory):os.makedirs(directory)with open(filepath, 'w', encoding='utf-8') as file:file.write(data)print(f"파일이 성공적으로 저장되었습니다: {filepath}")
🛒 장보기 전에 체크하면 유용한 건강식품 추천은, 천년삼 골드 6년근 홍삼정 프리미엄를 참고해보세요.
파일 입출력은 파이썬 프로그래밍의 기본 중의 기본이지만, 실제 프로젝트에서 매우 중요한 역할을 합니다. 오늘 배운 open(), read(), write() 함수들을 잘 활용하면 다양한 형태의 데이터를 효과적으로 관리할 수 있습니다. 특히 with 문을 이용한 안전한 파일 처리와 적절한 에러 처리는 실제 개발에서 꼭 기억해야 할 핵심 기술입니다. 여러분도 오늘 배운 내용을 바탕으로 직접 파일 입출력 관련 프로젝트를 만들어보시길 권장합니다. 다음 포스팅에서는 더 고급 파일 처리 기술에 대해 알아보겠습니다. 코딩하는곰이었습니다!
최근 당첨번호와 통계를 한눈에 보고 싶다면, AI 번호 추천과 QR코드 확인이 가능한 지니로또AI를 설치해보세요.
