파이썬/파이썬(python) 중급

[24-7 파이썬] 파일 읽기 read(), readline(), readlines()

Olivia-BlackCherry 2022. 9. 4. 17:09

파일 관련 메소드 중, 

오늘은

파일을 불러와서 읽는 방법을 소개한다. 

mode="r" 

모드는 r이지만, r은 디폴드 값이기 때문에 

따로 표시하지는 않겠다.

 

오늘 예제로 쓸

text.txt 파일의 내용이다.

 

 

read()

파일 전체를 읽는다.

with open("./Output/text.txt") as f:
    data= f.read()
print(data)

 

 

 readline()

파일의 첫 번째 줄을 읽는다.

with open("./Output/text.txt") as f:
    data= f.readline()
print(data)

파라미터로 size를 입력할 수 있는데, 

올 수 있는 바이트 숫자이다. 

with open("./Output/text.txt") as f:
    data= f.readline(7)
print(data)

 

 

readlines()

모든 파일의 내용을 한 줄씩 불러오되 

이것들을 리스트 형태로 반환한다.

with open("./Output/text.txt") as f:
    data= f.readlines()
print(data)

 

 

 

더 많은 파일 메소드를 알고 싶다면 

아래의 주소로 접속하면 된다. 

https://www.w3schools.com/python/python_ref_file.asp

 

Python File Methods

W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.

www.w3schools.com