IT

파이썬 파일 생성하고 읽고 쓰기

carnival6103 2025. 2. 8. 08:05
반응형

파이썬에서 파일을 생성하고 읽고 쓰는 방법은 매우 간단합니다. 아래는 파일을 생성하고, 읽고, 쓰는 방법에 대한 예시입니다.

1. 파일 생성 및 쓰기

파일을 생성하고 데이터를 쓰기 위해서는 open() 함수를 사용하여 파일을 열고, write() 메서드를 사용합니다. 파일을 열 때 모드를 지정해야 합니다:

  • 'w': 쓰기 모드 (파일이 존재하면 내용을 덮어씀)
  • 'a': 추가 모드 (파일이 존재하면 내용 뒤에 추가)
  • 'x': 배타적 생성 모드 (파일이 존재하면 오류 발생)
# 파일 생성 및 쓰기
with open('example.txt', 'w') as file:
    file.write("Hello, World!\n")
    file.write("This is a new file.\n")

2. 파일 읽기

파일을 읽기 위해서는 open() 함수를 사용하여 파일을 열고, read(), readline(), readlines() 메서드를 사용합니다. 파일을 열 때 모드를 지정해야 합니다:

  • 'r': 읽기 모드
# 파일 읽기
with open('example.txt', 'r') as file:
    content = file.read()
    print(content)

3. 파일에 데이터 추가

파일에 데이터를 추가하기 위해서는 open() 함수를 사용하여 파일을 열고, write() 메서드를 사용합니다. 파일을 열 때 모드를 지정해야 합니다:

  • 'a': 추가 모드
# 파일에 데이터 추가
with open('example.txt', 'a') as file:
    file.write("Appending new line.\n")

4. 파일 읽기 (라인 단위)

파일을 라인 단위로 읽기 위해서는 readline() 또는 readlines() 메서드를 사용합니다.

# 파일 라인 단위로 읽기
with open('example.txt', 'r') as file:
    for line in file:
        print(line.strip())  # 각 라인의 끝에 있는 개행 문자를 제거하고 출력

5. 파일 존재 여부 확인

파일이 존재하는지 확인하기 위해서는 os 모듈의 path.exists() 함수를 사용할 수 있습니다.

import os

if os.path.exists('example.txt'):
    print("File exists.")
else:
    print("File does not exist.")

예시: 파일 생성, 쓰기, 읽기, 추가

아래는 파일을 생성하고, 데이터를 쓰고, 읽고, 추가하는 전체 예시입니다:

# 파일 생성 및 쓰기
with open('example.txt', 'w') as file:
    file.write("Hello, World!\n")
    file.write("This is a new file.\n")

# 파일 읽기
with open('example.txt', 'r') as file:
    content = file.read()
    print("File content after creation:")
    print(content)

# 파일에 데이터 추가
with open('example.txt', 'a') as file:
    file.write("Appending new line.\n")

# 파일 라인 단위로 읽기
with open('example.txt', 'r') as file:
    print("File content after appending:")
    for line in file:
        print(line.strip())

이 예시에서는 파일을 생성하고 데이터를 쓰고, 읽고, 추가하는 과정을 모두 보여줍니다.

반응형