728x90
01. 사용자 입력
- 사용자가 값을 입력하게 하고 싶을 때 사용
input
a = input()
python
print(a)
python
※ input에 문자열을 입력하면 입력 메세지가 된다
number = input("숫자를 입력하세요 : ")
숫자를 입력하세요 : 3
※ input은 입력되는 모든 데이터를 문자열로 취급함
print(type(number))
<class 'str'>
02. 파일 처리
- 파일 처리를 위해서는 파일 열기(open)를 먼저 해야함
- 파일을 열면 파일 읽기(read) 또는 파일 쓰기(write)를 할 수 있음
- 파일 입력(읽기): 파일의 내용을 읽어들이는 것
- 파일 출력(쓰기): 파일에 새로운 내용을 추가하거나 새 파일을 생성하는 것
- 파일을 열면 파일 읽기(read) 또는 파일 쓰기(write)를 할 수 있음
03. 파일 객체 생성
- 파일객체 = open(파일이름(경로), 파일열기모드)
f = open("./new_file.txt", "w") #w: write 쓰기모드
f.close() #파일 닫기(파일을 열었으면 반드시 닫아야함)
※ 파일 모드에는 3가지(정확히는 6가지)가 있음
- 파일 열기 모드
- r(읽기)
- 파일을 읽기만 할 때
- 파일이 없으면 error
- w(쓰기)
- 파일에 내용을 쓸 때
- 파일이 없으면 새로 만듦
- 기존 파일에 있던 데이터를 완전히 지우고 다시 씀
- a(추가)
- 파일의 마지막에 새로운 내용을 추가할 때
- 파일이 없으면 새로 만듦
- r(읽기)
04. 파일 출력
f = open("new_file.txt", "w")
for i in range(1, 11):
f.write(str(i) + "\n")
f.close()
05. 파일 입력
# readLine()
f = open("new_file.txt", "r")
# 파일의 첫 번째 줄을 읽음
line = f.readline()
print(line)
f.close()
1
# 모든 줄을 읽고 싶다면 반복문 작성
f = open("new_file.txt", "r")
while True:
line = f.readline()
if not line:
break
# 파일 줄 끝에 \n이 있으므로 빈 줄이 같이 출력됨
# print(line)
# ver1
# print(line, end = "")
# ver2 문자열 앞뒤의 여백을 제거
print(line.strip())
f.close()
1
2
3
4
5
6
7
8
9
10
# readlines() : 파일의 모든 줄을 읽어서 각각의 줄을 요소로 갖는 리스트가 반환됨
f = open("new_file.txt", "r")
lines = f.readlines()
for line in lines:
print(line)
f.close()
1
2
3
4
5
6
7
8
9
10
print(lines)
['1\n', '2\n', '3\n', '4\n', '5\n', '6\n', '7\n', '8\n', '9\n', '10\n']
# read() : 파일 내용 전체를 문자열로 반환
f = open("new_file.txt", "r")
data = f.read()
print(data)
f.close()
1
2
3
4
5
6
7
8
9
10
data
'1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n'
06. 파일 추가
f = open("new_file.txt", "a")
for i in range(11, 20):
f.write(str(i) + "\n")
f.close()
07. with문
- 파일 사용이 끝난 다음에는 반드시 close()로 파일을 닫아줘야 함
- 자동으로 파일을 닫아주는 문법이 with문
with open("new_file.txt", "r") as f:
data = f.read()
print(data)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
11
12
13
14
15
16
17
18
19
f.read()
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Cell In[39], line 1
----> 1 f.read()
ValueError: I/O operation on closed file.
※with문으로 인해 자동으로 파일이 닫혔으므로, 닫힌 파일을 읽을 수 없다는 에러 발생
728x90
'01_Python' 카테고리의 다른 글
44_클래스 (1) | 2025.01.10 |
---|---|
43_파이썬 내장함수 (0) | 2025.01.09 |
41_함수 (0) | 2025.01.08 |
40_제어문>제어문연습(2) (0) | 2025.01.08 |
39_제어문>리스트 내포(List comprehension) (0) | 2025.01.08 |