파일객체 = open(파일이름, 파일모드) # 파일 열기
파일객체.close() # 파일 객체 닫기
with open(파일이름, 파일모드) as 파일객체: # 파일을 사용한 뒤 자동으로 파일 객체를 닫아줌
파일매서드
활용예
file = open('hello.txt', 'r') # hello.txt 파일을 읽기 모드(r)로 열기. 파일 객체 반환
s = file.read() # 파일에서 문자열 읽기
print(s) # Hello, world!
file.close()
파일 한줄씩 읽기
with open('hello.txt', 'r') as file: # hello.txt 파일을 읽기 모드(r)로 열기
lines = file.readlines()
print(lines)
문자열이 저장된 words.txt 파일이 주어집니다(문자열은 한 줄로 저장되어 있습니다). words.txt 파일에서 문자 c가 포함된 단어를 각 줄에 출력하는 프로그램을 만드세요. 단어를 출력할 때는 등장한 순서대로 출력해야 하며 ,(콤마)와 .(점)은 출력하지 않아야 합니다.
file = open("words.txt", 'r') #읽기모드로 열기
sen = file.read() #문자열 읽기
abc = sen.split() #공백을 기준으로 리스트 생성
for i in abc: #리스트의 변수 i 에 대해
if 'c' in i: # c 가 있는 i
print(i.strip(',.')) #문장부호 빼고 프린트