View
2
Download
0
Category
Preview:
Citation preview
Variable,
Calculation,
Selection &
Loop
Function &
Data Type
Class,
Object &
GUI
Programming
File I/O,
Recursion,
Sort &
Search
Turtle
Graphics
Python for
Computational
Thinking[파일 입출력]을
이용한
컴퓨팅 사고력
구 분 모드(mode) 명 칭 설 명
기본
모드
r 읽기(기본 값) read 파일의 처음부터 읽는다.
r+ 읽기 + 쓰기 read 파일을 읽고 쓸 수 있다.
w 쓰기 write파일의 처음부터 쓴다. 만약 파일이 없으면 생성하
고 존재하면 기존의 파일 내용은 삭제한다.
a쓰기 +
이어쓰기append 파일의 끝에 쓴다. 만약 파일이 없으면 생성한다.
파일
종류
t 텍스트 text 텍스트 파일
b 바이너리 binary 이진 파일
형 식
fileobject = open( “filename”, “mode”)...fileobject.close()
fileobject.write(“파일에 쓰기 위한 문자(데이터)”)
Shell
>>> f = open(“text.txt”, “w”)>>> f.write(“Nice to meet you!”)17>>> f.close()
>>> f = open(“googoodan.txt”)>>> line = f.readline()>>> while line :print(line, end= ‘ ’)line = f.readline()2 * 1 = 22 * 2 = 42 * 3 = 62 * 4 = 82 * 5 = 10>>> f.close()
>>> f = open(“text.txt”, “r”)>>> f.read()‘Nice to meet you!’>>> f.close()
Shell
>>> f = open(“googoodan.txt”)
>>> lines = f.readlines()
>>> for line in lines :
print(line, end= ‘ ’)
2 * 1 = 2
2 * 2 = 4
2 * 3 = 6
>>> f.close()
>>> f = open(“googoodan.txt”)
>>> lines = f.readlines()
>>> for line in lines :
line = line.rstrip()
print(line, end= ‘ ’)
2 * 1 = 2
2 * 2 = 4
2 * 3 = 6
>>> f.close()
Source
f1 = open(“words.txt”, “w”)
f1.write(“Nice to meet you!”)
f1.close()
f2 = open(“words.txt”, “r”)
for i in f2 :
i = i.rstrip() # 공백 문자를 분리자로 설정
word_list = i.split()
for j in word_list :
print(j)
f2.close()
Shell
Nice
to
meet
you!
Source
f3 = open(“numbers.txt”, “w”)
for i in range(10) :
f3.write(str(i)+“”)
f3.close()
Shell
>>> f3 = open(“numbers.txt”, “r”)
>>> f3.read()
‘0 1 2 3 4 5 6 7 8 9’
>>> f3.close()
Source
from tkinter import *from tkinter.filedialog import askopenfilenamefrom tkinter.filedialog import asksaveasfilename
fd = askopenfilename()if ( fd != None) :
f3 = open(fd, “r”)fr = f3.readlines()
for line in fr :line = line.rstrip()print(line, end= ‘ ’)
f3.close()
Shell
Hi!Nice to meet you!I'm Python
Shell
>>> f = open(“text.txt”, “r”)>>> f.tell()0>>> f.read()‘Nice to meet you!’>>> f.tell()17>>> f.read(4)‘Nice’>>> f.tell()4>>> f.seek(0)0>>> f.close()
Recommended