[Python] File Handling Start

BioinformaticsAndMe







File handling


: 파이썬 파일 처리에는 파일 생성/읽기/업데이트/삭제 등의 여러 기능이 존재

: 파일처리를 위해선 2가지 매개변수(파일명, 모드)를 갖는 'open() 함수'를 사용

: 파일 open에는 6가지 모드(mode)가 존재

1) "r" - Read - 파일 읽기(기본값)

2) "a" - Append - 파일 덧붙이기

3) "w" - Write - 파일 쓰기

4) "x" - Create - 특정 파일 생성

5) "t" - Text - 텍스트 모드(기본값)

6) "b" - Binary - 바이너리 모드(이미지 등)

# 파이썬 파일 읽기 예제

f = open("demofile.txt")


# 위 코드와 같음 (기본값이라 생략됨)

f = open("demofile.txt", "rt")




1. 파이썬 Read


demofile.txt

# demofile.txt 파일 읽기

f = open("demofile.txt", "r")

print(f.read())

Hello! Welcome to demofile.txt This file is for testing purposes. Good Luck!

# read(숫자)로 반환되는 문자수를 지정할 수 있음

f = open("demofile.txt", "r") print(f.read(5))

Hello

# readline() 메소드를 통해, 파일의 한 줄만을 반환

f = open("demofile.txt", "r") print(f.readline())

Hello! Welcome to demofile.txt

# 파일 처리가 끝난 뒤, 반드시 close() 메소드를 사용함

f = open("demofile.txt", "r") print(f.readline()) f.close()

Hello! Welcome to demofile.txt




2. 파이썬 Append


# 파일 끝에 덧붙이기

f = open("demofile2.txt", "a") f.write("Now the file has more content!") f.close() # 덧붙여진 파일을 다시 읽고, 결과 확인 f = open("demofile2.txt", "r") print(f.read())

Hello! Welcome to demofile2.txt This file is for testing purposes. Good Luck!Now the file has more content!




3. 파이썬 Write


# 파일 생성하고 쓰기

f = open("demofile3.txt", "w") f.write("Woops! I have deleted the content!") f.close()

# 쓰여진 파일을 읽고, 결과 확인 f = open("demofile3.txt", "r") print(f.read())

Woops! I have deleted the content!





#Reference

1) https://www.w3schools.com/python/python_file_handling.asp

2) https://data-flair.training/blogs/file-handling-in-python/





[Python] File Handling End

BioinformaticsAndMe

'Python' 카테고리의 다른 글

[Python] PyMongo 데이터베이스 만들기  (0) 2020.01.09
[Python] PyMongo 설치  (0) 2020.01.02
[Python] 표준 입력 (User Input)  (0) 2019.12.12
[Python] 파이썬 함수 (Function)  (0) 2019.12.05
[Python] 파이썬 반복문  (0) 2019.11.28

+ Recent posts