Repository navigation
Expand file tree
/
Copy pathreadEx.py
More file actions
48 lines (40 loc) · 1.94 KB
/
Copy pathreadEx.py
File metadata and controls
48 lines (40 loc) · 1.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# 파일 읽기 — 읽으려면 먼저 읽을 파일이 있어야 한다
import os
if not os.path.exists('output/memo2.txt'):
# writeEx.py 를 아직 안 돌렸다면 여기서 만들어 준다.
# "필요한 것이 없으면 먼저 확인한다" 는 파일을 다루는 코드의 기본입니다.
print('※ output/memo2.txt 가 없어 writeEx.py 를 먼저 실행합니다')
os.makedirs('output', exist_ok=True)
with open('output/memo2.txt', 'w', encoding='utf-8') as f:
f.write('첫 줄\n둘째 줄\n추가된 줄\n')
print('---------- read() : 통째로 문자열 하나로 ----------')
with open('output/memo2.txt', 'r', encoding='utf-8') as f:
content = f.read()
print(repr(content))
print(content)
print('---------- readlines() : 줄 단위 리스트로 ----------')
with open('output/memo2.txt', 'r', encoding='utf-8') as f:
lines = f.readlines()
print(lines) # 줄바꿈 문자가 그대로 붙어 있다
print([line.strip() for line in lines]) # strip() 으로 제거
print('---------- for 순회 : 가장 권장 ----------')
# 파일 전체를 메모리에 올리지 않고 한 줄씩 읽는다. 큰 파일에서 중요하다.
with open('output/memo2.txt', 'r', encoding='utf-8') as f:
for i, line in enumerate(f, start=1):
print(f'{i}: {line.strip()}')
print('---------- readline() : 한 줄씩 직접 ----------')
with open('output/memo2.txt', 'r', encoding='utf-8') as f:
first = f.readline()
second = f.readline()
print('1행 :', first.strip())
print('2행 :', second.strip())
print('---------- 파일이 없으면? ----------')
try:
with open('output/없는파일.txt', 'r', encoding='utf-8') as f:
f.read()
except FileNotFoundError as e:
print('FileNotFoundError :', e)
print('---------- 존재 확인 ----------')
import os
print('memo2.txt 있나 :', os.path.exists('output/memo2.txt'))
print('없는파일 있나 :', os.path.exists('output/없는파일.txt'))