728x90
반응형
27. 파일 사용
* 파일 작업이 끝나면 반드시 .close()로 객체를 닫아줘야 한다.
27.1 파일에 문자열 쓰기, 읽기
# hello.txt 파일을 쓰기모드(w)로 열기. 파일 객체 반환
file = open('hello.txt', 'w')
# 파일에 문자열 저장
file.write('Hello, world!')
# 파일 객체 닫기
file.close()
# 변수 = 파일객체.read()
# hello.txt 파일을 읽기 모드(r)로 열기. 파일 객체 반환
file = open('hello.txt', 'r')
# 파일에서 문자열 읽기
s = file.read()
print(s)
Hello, world!
# 파일 객체 닫기
file.close()
print(line)
Hello, world!
# 자동으로 파일 객체 닫기
with open('hello.txt', 'r') as file: # hello.txt 파일을 읽기 모드(r)로 열기
s = file.read() # 파일에서 문자열 읽기
print(s) # Hello, world!
Hello, world!
27.2 문자열 여러 줄을 파일에 쓰기, 읽기
# 반복문으로 문자열 여러 줄을 파일에 쓰기
with open('hello.txt', 'w') as file:
for i in range(3):
file.write('Hello, world! {0}\n'.format(i))
# 리스트에 들어있는 문자열을 파일에 쓰기
lines = ['안녕하세요.\n', 'python\n', '코딩도장\n']
with open('hello.txt', 'w') as file:
file.writelines(lines)
# 파일의 내용을 한 줄 씩 리스트로 가져오기
with open('hello.txt', 'r') as file:
lines = file.readlines()
print(lines)
['안녕하세요.\n', 'python\n', '코딩도장\n']
# 파일 내용 한줄씩 읽기
with open('hello.txt', 'r') as file:
line = None
while line != '':
line = file.readline()
print(line.strip('\n'))
안녕하세요.
python
코딩도장
# 파일 내용 줄 단위로 읽기
with open('hello.txt', 'r') as file:
for line in file:
print(line.strip('\n'))
안녕하세요.
python
코딩도장
# 파일 객체는 이터레이터
file = open('hello.txt', 'r')
a, b, c = file
print(a, b, c)
# 결과가 교재랑 다르게 나오는데 다같이 확인
# 교재 : ('안녕하세요\n', 'pyhon\n','코딩도장\n')
안녕하세요.
python
코딩도장
27.3 파이선 객체를 파일에 저장하기, 가져오기
import pickle
name = 'james'
age = 17
address = '서울시 서초구 반포동'
scores = {'korean': 90, 'english': 95, 'math': 85, 'science': 82}
with open('james.p', 'wb') as file: # james.p 파일을 바이너리 쓰기모드(wb)로 열기
pickle.dump(name, file)
pickle.dump(age, file)
pickle.dump(address, file)
pickle.dump(scores, file)
print(name)
print(age)
print(address)
print(scores)
james
17
서울시 서초구 반포동
{'korean': 90, 'english': 95, 'math': 85, 'science': 82}
27.5 연습문제: 파일에서 10 이하인 단어 개수 세기
words = ['anonymously', 'compatibility', 'dashboard', 'experience', 'photography', 'spotlight']
with open('words.txt', 'w') as file:
for i in words:
file.write(i + '\n')
with open('words.txt', 'r') as file:
for word in file:
if len(word) <= 10:
print(word)
dashboard
spotlight
27.6 심사문제 : 특정 문제가 들어있는 단어 찾기
words = 'Fortunately, however, for the reputation of Asteroid B-612, ' \
'a Turkish dictator made a law that his subjects, under pain of death, ' \
'should change to European costume. So in 1920 the astronomer gave his demonstration ' \
'all over again, dressed with impressive style and elegance. ' \
'And this time everybody accepted his report.'
with open('findWord.txt', 'w') as file:
file.write(words)
with open('findWord.txt', 'r') as file:
content = file.readlines()
for i in content[0].split(' '):
if i.__contains__('c'):
print(i.strip(',.'))
dictator
subjects
change
costume
elegance
accepted
728x90
반응형
'Language > Python' 카테고리의 다른 글
[코딩도장]29. 함수 사용 (0) | 2022.03.24 |
---|---|
[코딩도장]28.회문판별과 N-gram 만들기 (0) | 2022.03.23 |
[코딩도장]26.세트사용하기 (0) | 2022.03.21 |
[코딩도장]25.딕셔너리응용 (0) | 2022.03.18 |
[코딩도장]24.문자열 응용 (0) | 2022.03.16 |