2020. 5. 3. 22:52ㆍ프로그래밍(Programming)/Python
Python 의 파일 입출력은 다른 언어에 비해서 굉장히 간단한 편이다.
오늘은 아래 3줄짜리 파일을 가지고 테스트를 해본다.
파일 이름은 test_file.txt, 내용은 아래와 같다.
1. Test File Read 2. Hello World 3. Reading file with python is easy. |
먼저 Python에서 파일 입출력을 위해서는 open이라는 built-in 함수(내장 함수)를 알아야 한다.
나는 3.6 가상환경에서 아래 프로그램을 작성하기 때문에, 3.6 version open()함수 설명 링크를 남긴다.
https://docs.python.org/ko/3.6/library/functions.html#open

일단 가장 많이 쓰는 parameter는 아래 2가지다.
file: 파일 경로
mode: 어떻게 파일을 읽고 쓸 것인지
========= =============================================================== Character Meaning --------- --------------------------------------------------------------- 'r' open for reading (default) 'w' open for writing, truncating the file first 'x' create a new file and open it for writing 'a' open for writing, appending to the end of the file if it exists 'b' binary mode 't' text mode (default) '+' open a disk file for updating (reading and writing) 'U' universal newline mode (deprecated) ========= =============================================================== The default mode is 'rt' (open for reading text). For binary random access, the mode 'w+b' opens and truncates the file to 0 bytes, while 'r+b' opens the file without truncation. The 'x' mode implies 'w' and raises an `FileExistsError` if the file already exists. |
그래서 보통 텍스트 파일을 읽는 경우, 단순하게 아래와 같이 읽을 수 있다.
def main():
txt_file = open('test_file.txt')
# txt_file = open('test_file.txt', 'r')
lines = txt_file.readlines()
for line in lines:
print(line)
txt_file.close()
if __name__ == "__main__":
main()
위 코드에서는 open을 mode없이 호출하고 있는데, 실행 결과를 보면 open함수의 mode parameter의 기본값이 'r'이라는 것을 확인할 수 있다.
실행 결과
1. Test File Read 2. Hello World 3. Reading file with python is easy. |
위 실행 결과를 보면, 1, 2이후에 빈줄이 하나씩 보이는데, readlines() 함수가 개행문자를 포함하여 텍스트 파일을 읽고 있음을 알 수 있다.
나 같은 경우는 보통 아래와 같이 open을 with 키워드와 함께 사용하여 close()를 호출해주는 번거로움을 없앤다.
또한 open의 결과가 iterable하기 때문에 반복문의 대상 object로 쓸 수 있다.
iterable하다는 것을 확인하기 위해 is_iterable()함수를 만들고, int type인 object와 비교하여 iterable 하다는 것을 확인하였다.
결론부터 말하자면, 읽어들인 파일을 아래와 같이 for 문을 이용하여 한줄씩 출력 할 수 있다.
그리고 출력시에, 각 줄에서 개행문자를 제거하기 위해 strip() 함수를 호출했다.
def is_iterable(obj):
try:
iter(obj)
except TypeError:
return False
return True
def main():
with open('test_file.txt', 'r') as f:
result = is_iterable(f)
print("File object is iterable? " + str(result))
a = 0
result = is_iterable(a)
print("File object is iterable? " + str(result))
for line in f:
print(line.strip())
if __name__ == "__main__":
main()
실행 결과
File object is iterable? True File object is iterable? False 1. Test File Read 2. Hello World 3. Reading file with python is easy. |