Text files · 텍스트 파일
Why files?
- Variables vanish when a program ends. A file keeps data on disk.
- Files let you save results and read them back later.
- They also hold more data than you would type by hand.
파일이 필요한 이유
- 변수는 프로그램이 종료되면 사라집니다. 파일은 데이터를 디스크에 유지합니다.
- 파일을 통해 결과를 저장한 후 나중에 다시 읽을 수 있습니다.
- 또한 수동으로 입력할 수 있는 것보다 더 많은 데이터를 저장할 수 있습니다.
Open, use, close
open(name, mode)opens a file. The mode says what you will do."r"reads,"w"writes a fresh file (replacing any old text),"a"adds to the end.- Every file you open must be closed when you finish.
열기, 사용, 닫기
open(name, mode)는 파일을 엽니다. 모드는 어떤 작업을 수행할지 나타냅니다."r"는 읽으며,"w"는 새 파일을 작성합니다(기존 텍스트를 교체함),"a"는 끝부분에 추가합니다.- 열었던 모든 파일은 작업을 마칠 때 반드시 닫아야 합니다.
The with block
with open(...) as f:opens the file and closes it for you.- All the work goes in the indented block.
- This is the safest way — the file is never left open.
with 블록
with open(...) as f:는 파일을 열고 자동으로 닫아줍니다.- 모든 작업은 줄을 들여쓴 블록 내에 이루어집니다.
- 이는 가장 안전한 방법입니다 — 파일이 열려 있는 상태로 남지 않습니다.
with open("greeting.txt", "w") as f:
f.write("Hi there\n")
with open("greeting.txt", "r") as f:
print(f.read())
Reading the lines
f.read()returns the whole file as one string.for line in f:reads it one line at a time.- Each line keeps its newline, so use
line.strip()to remove it.
줄 읽기
f.read()는 전체 파일을 하나의 문자열로 반환합니다.for line in f:는 이를 줄 단위로 읽습니다.- 각 줄에는 줄바꿈 문자가 포함되므로 제거하려면
line.strip()를 사용하십시오.
with open("fruit.txt", "w") as f:
f.write("apple\npear\n")
with open("fruit.txt", "r") as f:
for line in f:
print(line.strip())
In Cambridge pseudocode
- The exam uses
OPENFILE,WRITEFILE,READFILE, andCLOSEFILE.
캐미지아 가위코드에서
- 시험에서는
OPENFILE,WRITEFILE,READFILE, 그리고CLOSEFILE를 사용합니다.
OPENFILE "notes.txt" FOR WRITE
WRITEFILE "notes.txt", "Hello"
CLOSEFILE "notes.txt"
OPENFILE "notes.txt" FOR READ
READFILE "notes.txt", line
CLOSEFILE "notes.txt"
OUTPUT line
Common mistakes
- Use
with open(...) as f:so the file closes itself. "w"erases the file first;"a"adds to the end.
흔한 실수
with open(...) as f:를 사용하여 파일이 자동으로 닫히게 하십시오."w"는 파일을 먼저 지우고;"a"는 끝부분에 추가합니다.
Now you try
- This playground keeps files between runs, so write the file first, then read it in the same task.
- Press Check answer to test your code.
이제 직접 해보기
- 이 플레이그라운드는 실행 간에 파일을 유지하므로, 먼저 파일을 작성한 후 같은 작업 내에서 읽으십시오.
- Answer 확인 버튼을 눌러 코드를 테스트하세요.
Reading a file · 파일 읽기
A file is used in three steps: open, read, close. · 파일을 다루는 과정은 세 단계로 구성됩니다: 열기, 읽기, 닫기.
In one run: write the two lines Hello and World to a file called notes.txt, then open it again, read it, and print what you read. · 한 번의 실행에서 두 줄 Hello과 World을 notes.txt라는 이름의 파일에 쓰고, 다시 열어서 읽고, 읽은 내용을 print합니다.
Click Run to see the output here. · 출력을 보려면 '실행'을 클릭하세요.
Write three lines to a file, then read it back and count the lines with a loop. Store the count in count (the answer is 3). · 세 줄을 파일에 쓴 뒤 다시 읽어와 루프로 줄 수를 세세요. 그 개수를 count에 저장합니다 (정답은 3).
Click Run to see the output here. · 출력을 보려면 '실행'을 클릭하세요.
Write the numbers 10, 20, 30 to a file, one per line. Then read them back, convert each line with int(...), and add them up in total (the answer is 60). · 숫자 10, 20, 30를 한 줄에 하나씩 파일에 니다. 다시 읽어와 각 줄을 int(...)으로 변환한 뒤 total에 합산합니다 (정답은 60).
Click Run to see the output here. · 출력을 보려면 '실행'을 클릭하세요.