본문 바로가기
강의들을건대 2학년 2학기/프로그래밍을통한문제해결

프로그래밍을통한문제해결 15주차 [ 파이썬, 파일, 모듈]

by 공부해열 2022. 12. 15.

15주차도 파이썬 코딩 실습을 했습니다. 이번 실습은 파일을 만들고, 열고, 닫고, 수정하는 코딩을 배웠습니다. 16주차는 기말고사라서 마지막 포스팅입니다.

파일 열고 닫기

파일열기

홍길동 010-1234-5678
김철수 010-1234-5679
김영희 010-1234-5680
ㄴTXT에 따로 타이핑후 경로 'C:\'에 저장

#경로에있는 파일 열기
infile = open("C:\프통문15주차.txt", "r",encoding="UTF8")
lines = infile.read() 
print(lines)

#엔터값까지 서식그대로 옮겨서 파일 열기
infile = open("C:\프통문15주차.txt", "r",encoding="UTF8")
lines = infile.readlines() 
print(lines)

#줄 뛰어쓰기 파일열기
infile = open("C:\프통문15주차.txt", "r",encoding="UTF8")
line = infile.readline() 
print(line)
line = infile.readline() 
print(line)
line = infile.readline() 
print(line)
infile.close()

#띄우지않고 한줄씩 읽기
infile = open("C:\프통문15주차.txt", "r",encoding="UTF8")
line = infile.readline().rstrip()
while line != "": 
    print(line)
    line = infile.readline().rstrip()
infile.close()

#FOR문 이용 띄우지 않고 한줄씩 읽기
infile = open("C:\프통문15주차.txt", "r",encoding="UTF8")
for line in infile:
line = line.rstrip()
print(line)
infile.close() 

#파일에 데이터 쓰기 w모드
#(기존에 파일이 없으면 생성, 있으면 내용삭제 후 새로 기록)
outfile = open("C:\프통문15주차.txt", "w")
outfile.write("홍길동 010-1234-5678")
outfile.write("김철수 010-1234-5679")
outfile.write("김영희 010-1234-5680")
outfile.close()

#\n(백슬래쉬n)을 넣으면 뛰어쓰기 됨
outfile = open("C:\새로만들어지나.txt", "w")
outfile.write("홍길동 010-1234-5678\n")
outfile.write("김철수 010-1234-5679\n")
outfile.write("김영희 010-1234-5680\n")
outfile.close()

#C:\경로에 'proverbs.txt'생성 후 아래내용 입력
All's well that ends well.
Bad news travels fast.
Well begun is half done.
Birds of a feather flock together.

#파일에 단어읽기
infile = open("C:\proverbs.txt", "r")
for line in infile:
    line = line.rstrip()
    word_list = line.split()
    for word in word_list:
        print(word);
infile.close()

#SOLUTION
# 입력 파일 이름과 출력 파일 이름을 받는다. 
infilename = input("입력 파일 이름: ");
outfilename = input("출력 파일 이름: ");
# 입력과 출력을 위한 파일을 연다. 
infile = open(infilename, "r”, encoding=“UTF8”)
outfile = open(outfilename, "w")
# 전체 파일을 읽는다. 
s = infile.read()
# 전체 파일을 쓴다. 
outfile.write(s)
# 파일을 닫는다.
infile.close() 
outfile.close()

#객체 생성 코드
class Car:
    def drive(self):
        self.speed = 10
myCar = Car()
myCar.color = "blue"
myCar.model = "E-Class"
myCar.drive()
print(myCar.speed)


기말고사는 비대면 시험입니다. 5문제 중 골라서 2문제를 풀면 되고 소스파일, 실행화면 캡쳐 2쌍 총 4개의 파일을 업로드 하여야합니다.


댓글