Dev Hyeri

기술스택/Python

[ 파이썬 ] 파일 오픈 함수 file I/O

_hyeri 2023. 9. 5. 21:28

 

파일 오픈 함수 

with open("demofile.txt", "r") as f:

 data = f.readlines()

 

 

 

 

 

 

1. 파일 열기 함수


 

  • 상대경로 파일 열기
f = open("demofile.txt", "r")
print(f.read())

 

  • 절대경로 파일 열기
f = open("D:\\myfiles\welcome.txt", "r")
print(f.read())

 

 

 

 

2. readline


 

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

 

 

 

 

3.오픈한 파일 시스템 상에 오픈 상태로 두지 말고 닫기 (⭐방법 1)


 

  • 방법 1
f = with open("demofile.txt", "r") 
print(f.readline())

 

 

  • 방법 2
f = open("demofile.txt", "r")
print(f.readline())
f.close()

 

 

 

 

"r" - Read - Default value. Opens a file for reading, error if the file does not exist

"a" - Append - Opens a file for appending, creates the file if it does not exist

"w" - Write - Opens a file for writing, creates the file if it does not exist

"x" - Create - Creates the specified file, returns an error if the file exists

"t" - Text - Default value. Text mode

"b" - Binary - Binary mode (e.g. images)