[Python] 파일 입출력 (File I/O) + with 문법
2022. 6. 13. 15:40ㆍLanguages/Python
파일 열기 (Open)
- open() 함수를 이용하여 파일을 열 수 있습니다.
- 읽기 전용으로 열고 싶으면 'r', 쓰기 전용으로 열고 싶으면 'w'을 인자로 줍니다.
_file = open(file = "ex1.csv", mode = 'r')
...
# 작업을 마쳤다면 닫아줍니다.
_file.close()
파일 읽기 (Read)
- readline() 메소드를 이용하여 한 줄씩 차례대로 읽을 수 있습니다.
_file.readline() # 'a, b, c, d, message\n'
_file.readline() # '1, 2, 3, 4, hello\n'
_file.readline() # '5, 6, 7, 8, world\n'
_file.readline() # '9, 10, 11, 12, foo\n'
_file.readline() # '' -> 마지막 라인까지 모두 읽음
- readlines()를 통해, 한 줄씩 읽어 리스트로 변환할 수 있습니다.
- 리스트로 반환하기 때문에 파일 크기가 크면 메모리 부족 문제가 생길 수 있습니다.
for line in _file.readlines():
print(line)
_file.close()
# 출력
# a, b, c, d, message
# 1, 2, 3, 4, hello
# 5, 6, 7, 8, world
# 9, 10, 11, 12, foo
- 따라서, 일반적으로는 Lazy loading인 다음 방법을 사용합니다.
for line in _file:
print(line)
_file.close()
# 'a, b, c, d, message'
# '1, 2, 3, 4, hello'
# '5, 6, 7, 8, world'
# '9, 10, 11, 12, foo'
- read()를 통해 모든 라인을 한 번에 읽을 수 있습니다.
print(_file.read())
_file.close()
# a, b, c, d, message
# 1, 2, 3, 4, hello
# 5, 6, 7, 8, world
# 9, 10, 11, 12, foo
파일 쓰기 (Write)
- 파일을 쓰기 전용(w)으로 열어줍니다.
_file = open(file = "myTest.txt", mode = 'w')
- write() 메소드를 통해 파일에 쓸 수 있습니다. 이 때 쓰기 작업은 처음부터 다시 덮어쓰는 작업입니다.
_file.write('''
It was the best of times, it was the worst of times,
it was the age of wisdom, it was the age of foolishness,
it was the epoch of belief, it was the epoch of incredulity,
it was the season of Light, it was the season of Darkness,
it was the spring of hope, it was the winter of despair,
we had everything before us, we had nothing before us,
we were all going direct to Heaven, we were all going direct the other way -
in short, the period was so far like the present period,
that some of its noisiest authorities insisted on its being received,
for good or for evil, in the superlative degree of comparison only.
Tale of Two Cities
by Charles Dickens
''')
_file.close() # 닫아주지 않으면 파일이 저장되지 않습니다.
- 다시 파일을 읽어, 잘 저장되었는지 확인해봅니다.
_file = open(file = "myTest.txt", mode = 'r')
print(_file.read())
_file.close()
# 출력
'''
It was the best of times, it was the worst of times,
it was the age of wisdom, it was the age of foolishness,
it was the epoch of belief, it was the epoch of incredulity,
it was the season of Light, it was the season of Darkness,
it was the spring of hope, it was the winter of despair,
we had everything before us, we had nothing before us,
we were all going direct to Heaven, we were all going direct the other way -
in short, the period was so far like the present period,
that some of its noisiest authorities insisted on its being received,
for good or for evil, in the superlative degree of comparison only.
Tale of Two Cities
by Charles Dickens
'''
with
- 파일 사용을 마칠 때마다 close()를 해주는 것이 번거롭다면, with 구문을 사용하면 편리합니다.
with open("myTest.txt") as _file:
print(_file.read())
- 위의 with 구문에서는 with 블록 내의 코드가 종료됨과 동시에, 파일을 자동으로 close() 처리 해줍니다.
- 파일 입출력에서는 with 구문을 활용하는 것이 편리합니다.
# txt 파일을 읽고, 각 라인의 앞에 라인 번호 매기기
def AddNums(fileName):
result = []
with open(fileName) as _file:
for number, line in enumerate(_file):
result.append(str(number) + ". " + line)
return result
result = AddNums("myTest.txt")
result
# 결과
'''
['0. \n',
'1. It was the best of times, it was the worst of times,\n',
'2. it was the age of wisdom, it was the age of foolishness,\n',
'3. it was the epoch of belief, it was the epoch of incredulity,\n',
'4. it was the season of Light, it was the season of Darkness,\n',
'5. it was the spring of hope, it was the winter of despair,\n',
'6. we had everything before us, we had nothing before us,\n',
'7. we were all going direct to Heaven, we were all going direct the other way -\n',
'8. in short, the period was so far like the present period,\n',
'9. that some of its noisiest authorities insisted on its being received,\n',
'10. for good or for evil, in the superlative degree of comparison only.\n',
'11. \n',
'12. Tale of Two Cities\n',
'13. by Charles Dickens\n']
'''
728x90
반응형
'Languages > Python' 카테고리의 다른 글
[Python] Generator, Enumerate, Zip (0) | 2022.06.12 |
---|---|
[Python] Iterable, Iterator (0) | 2022.06.12 |
[Python] Lambda 식 (0) | 2022.06.12 |
[Python] While / else (0) | 2022.06.12 |
[Python] 파이썬을 통해 구현한 DFS와 BFS (0) | 2022.05.14 |