python/중급
file read
알 수 없는 사용자
2021. 8. 22. 16:50
open function 설명
open(file_path, mode)
파라메터 | 설명 |
file_path | 파일이 저장되어있거나 저장될 경로 |
mode | r: read, w: write 모드 |
일단 아래 내용의 파일을 읽어보자.
zen_python.txt
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
1. 파일 읽기 기본
with open("python_zen.txt", "r") as rf:
data = rf.read()
print(data)
"""
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
"""
이렇게 하면 파일 내용 전체가 data에 저장이 된다.
2. 파일 읽기 한줄 씩 (추천)
with open("python_zen.txt", "r") as rf:
lines = rf.readlines()
for line in lines:
print(line)
1번보다는 2번방식을 추천한다.
1번방식은 파일 용량이 커지면 파일을 한꺼번에 읽다보면 메모리를 모두 소비하게 되므로
2번 방식으로 한줄씩 읽고 처리하는게 메모리 관리에 효율적이다.