PYTHON
파일 사용하기
yuurimingg
2023. 12. 26. 23:11
In [3]:
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity="all"
파일에 문자열 쓰기, 읽기¶
파일에 문자열 쓰기¶
- 파일객체 = open(파일이름, 파일모드)r : 읽기
- w : 쓰기
- 파일객체.write("문지열")
- 파일객체.close()
In [1]:
file = open('hello.txt', 'w')
file.write('hello, world!')
file.close()
파일에서 문자열 읽기¶
- 변수 = 파일객체.read()
In [4]:
file = open('hello.txt', 'r')
s = file.read()
s
file.close()
Out[4]:
'hello, world!'
자동으로 파일 객체 닫기¶
- with open("파일명", "코드") as 파일객체
In [6]:
with open('hello.txt', 'r') as f:
s = f.read()
s
Out[6]:
'hello, world!'
문자열 여러 줄을 파일에 쓰기, 읽기¶
반복문으로 문자열 여러 줄을 파일에 쓰기¶
In [7]:
with open('hello.txt', 'w') as file:
for i in range(3):
file.write('hello, world!{}\n'.format(i)) # \n이 없으면 한 줄로
Out[7]:
15
Out[7]:
15
Out[7]:
15
리스트에 들어있는 문자열을 파일에 쓰기¶
- 파일객체.writelines(문자열리스트)
In [8]:
lst = ['cat\n', 'dog\n', 'rabbit\n']
with open("hello.txt", 'w') as file:
file.writelines(lst)
파일의 내용을 한 줄씩 리스트로 가져오기¶
- 변수 = 파일객체.readlines()
In [9]:
with open("hello.txt", 'r') as file:
lst2 = file.readlines()
print(lst2)
['cat\n', 'dog\n', 'rabbit\n']
파일의 내용을 한 줄씩 읽기¶
- 변수 = 파일객체.readline()
In [10]:
with open('hello.txt', 'r') as file:
line = None
while line != '':
line = file.readline()
print(line.strip('\n')) # 이미 '\n 이 있고 print로 인해 줄 바꿈이 2번 발생하므로 하나는 제거
cat
dog
rabbit
for반복문으로 파일의 내용을 줄 단위로 읽기¶
In [11]:
with open('hello.txt', 'r') as file:
for line in file:
print(line.strip('\n'))
cat
dog
rabbit
파이썬 객체를 파일에 저정하기, 가져오기¶
- pickle 모듈 이용
파이썬 객체를 파일에 저장하기¶
- wb : 바이너리 쓰기 모드
- pickle.dump(변수명, 파일객체)
In [12]:
import pickle
name = "james"
age = 17
address = "서울시 서초구 반포동"
scores = {'kor' : 90, 'eng' : 95, 'mat' : 85, 'sci' : 82}
with open('james.p', 'wb') as file:
pickle.dump(name, file)
pickle.dump(age, file)
pickle.dump(address, file)
pickle.dump(scores, file)
파일에서 파이썬 객체 읽기¶
- rb : 바이너리 읽기 모드
- pickle.load(파일객체)
In [13]:
import pickle
with open('james.p', 'rb') as file:
name = pickle.load(file)
age = pickle.load(file)
address = pickle.load(file)
scores = pickle.load(file)
print(name)
print(age)
print(address)
print(scores)
james
17
서울시 서초구 반포동
{'kor': 90, 'eng': 95, 'mat': 85, 'sci': 82}
연습¶
동물 이름 입력 받아 파일에 넣기¶
In [15]:
while True:
name = input("동물 이름 입력 : ")
if name != '0000':
with open('animals.txt', 'a') as file:
file.write(name + '\n')
else:
break
동물 이름 입력 : cat
Out[15]:
4
동물 이름 입력 : dog
Out[15]:
4
동물 이름 입력 : 0000
연습문제 : 파일에서 10자 이하인 단어 개수 세기¶
단어가 줄 단위로 저장된 words.txt 파일이 주어집니다. 다음 소스 코드를 완성하여 10자 이하인 단어의 개수가 출력되게 만드세요.
In [16]:
lst = ['anonymously\n', 'compatibility\n', 'dashboard\n', 'experience\n',
'photography\n', 'spotlight\n', 'warehouse\n']
with open('words.txt', 'w') as file:
file.writelines(lst)
with open('words.txt', 'r') as file:
count = 0
words = file.readlines()
for word in words:
if len(word.strip('\n')) <= 10:
count += 1
count
Out[16]:
4
심사문제 : 특정 문자가 들어있는 단어 찾기¶
문자열이 저장된 words.txt 파일이 주어집니다(문자열은 한 줄로 저장되어 있습니다). words.txt파일에서 문자 c가 포함된 단어를 각줄에 출력하는 프로그램을 만드세요. 단어를 출력할 때는 등장한 순서대로 출력해야 하며 ,와.은 출력하지 않아야 합니다.
In [17]:
lst = ['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('words.txt', 'w') as file:
for i in range(len(lst)):
if i != len(lst)-1:
file.write(lst[i] + ', ')
else:
file.write(lst[i])
with open('words.txt', 'r') as file:
words = file.readline()
for word in words.split():
if 'c' in word:
print(word.strip(',.'))
Out[17]:
13
Out[17]:
9
Out[17]:
38
Out[17]:
49
Out[17]:
21
Out[17]:
100
Out[17]:
88
dictator
subjects
change
costume
elegance
accepted