개발/python

python 파일 읽고 쓰기

희운1205 2024. 5. 23. 10:42
반응형

python 파일 읽고 쓰기

1. 파일 열기
파일을 열기 위해 open() 함수를 사용하며 파일의 객체를 반환하고, 파일 모드를 지정할 수 있습니다. 

# 파일모드

'r': 읽기 모드 (기본값)
'w': 쓰기 모드 (파일 존재시 내용을 덮어씀)
'a': 추가 모드 (파일 끝에 내용을 추가)
'b': 이진 모드 (바이너리 파일을 다룰 때 사용)
't': 텍스트 모드 (기본값)

# 예제

# 기본 파일 읽기
[전체]
with open('example.txt', 'r') as file:
    content = file.read()
    print(content)

[한줄]
with open('example.txt', 'r') as file:
    for line in file:
        print(line.strip())  # 줄 끝의 줄바꿈 문자를 제거

[여러줄]
with open('example.txt', 'r') as file:
    lines = file.readlines()
    print(lines)
    
# 기본 파일 쓰기
with open('example.txt', 'w') as file:
    file.write("Hello, World!\n")
    file.write("This is a new file.\n")

# 파일에 내용 추가
with open('example.txt', 'a') as file:
    file.write("Adding a new line.\n")
    
# 이미지, 오디오 파일등을 다룰 때는 이진 모드('b') 사용시

[이진 파일 읽기]
with open('example.png', 'rb') as file:
    binary_content = file.read()
    print(binary_content)
    
[이진 파일 쓰기]
with open('example_copy.png', 'wb') as file:
    file.write(binary_content)


2. 파일 존재 여부 확인 및 예외 처리

import os

# 기본
file_path = 'example.txt'
if os.path.exists(file_path):
    with open(file_path, 'r') as file:
        content = file.read()
        print(content)
else:
    print(f"{file_path}가 존재하지 않습니다.")


# 예외처리
try:
    with open('example.txt', 'r') as file:
        content = file.read()
        print(content)
except FileNotFoundError:
    print("파일이 존재하지 않습니다.")
except Exception as e:
    print(f"에러가 발생했습니다.: {e}")

3. os 라이브러리로 할수 있는 것들

* 자세한건 공식 문서 참조 : https://docs.python.org/3/library/os.html

# 파일 및 디렉터리 조작
디렉터리 생성: os.mkdir(path)
재귀적 디렉터리 생성: os.makedirs(path)
디렉터리 삭제: os.rmdir(path)
재귀적 디렉터리 삭제: os.removedirs(path)
현재 작업 디렉터리 변경: os.chdir(path)
현재 작업 디렉터리 확인: os.getcwd()
파일 생성, 삭제, 이동
파일 삭제: os.remove(path)
파일 이름 변경/이동: os.rename(src, dst)
파일 복사: os.system('cp src dst') (Unix 계열) 또는 os.system('copy src dst') (Windows)
파일 및 디렉터리 속성
파일/디렉터리 존재 여부 확인: os.path.exists(path)
파일 여부 확인: os.path.isfile(path)
디렉터리 여부 확인: os.path.isdir(path)
파일 크기 확인: os.path.getsize(path)

# 환경 변수
환경 변수 가져오기: os.getenv(key, default=None)
환경 변수 설정: os.putenv(key, value)
환경 변수 제거: os.unsetenv(key)
프로세스 관리
프로세스 생성 및 실행
외부 명령 실행: os.system(command)
새 프로세스 생성: os.spawn* 함수들 (os.spawnl, os.spawnlp, os.spawnv, os.spawnvp 등)
새 프로세스 실행: os.exec* 함수들 (os.execl, os.execlp, os.execv, os.execvp 등)

#프로세스 정보
현재 프로세스 ID 확인: os.getpid()
부모 프로세스 ID 확인: os.getppid()
사용자 ID 확인: os.getuid() (Unix 계열)
그룹 ID 확인: os.getgid() (Unix 계열)

#파일 및 디렉터리 탐색
디렉터리 내용 리스트: os.listdir(path)
디렉터리 트리 탐색: os.walk(top, topdown=True, onerror=None, followlinks=False)
심볼릭 링크 및 하드 링크
심볼릭 링크 및 하드 링크 생성
심볼릭 링크 생성: os.symlink(src, dst)
하드 링크 생성: os.link(src, dst)
심볼릭 링크 읽기
심볼릭 링크 읽기: os.readlink(path)

#시스템 정보
운영 체제 이름: os.name
플랫폼 이름: os.uname() (Unix 계열)
시스템 부팅 시간: os.times()

#사용자와 권한
파일 권한 변경: os.chmod(path, mode)
파일 소유자 변경: os.chown(path, uid, gid)
사용자 ID 확인: os.getuid() (Unix 계열)
현재 사용자 이름 확인: os.getlogin()

#시간 관련
파일의 접근 및 수정 시간 변경: os.utime(path, times)
반응형