본문 바로가기
솔루션모음/파워 유저를 위한 파이썬 express 실습문제

[파워 유저를 위한 파이썬express] 10장 프로그래밍 programming 솔루션 답지

by 이얏호이야호 2023. 1. 8.

1.
f = open("proverbs.txt","r")
for i in range(3):
    print(f.readline())
f.close()

3.
import random
def random_line(fname):
    lines = open(fname).read().splitlines()
    return random.choice(lines)
print(random_line('proverbs.txt'))


5.
f = open('proverbs.txt' , 'r')
content = f.read()
f.close()
mylist = content.split()
mylist.insert(1, "line 2-1")

f = open('myfile.txt' , 'w')
for line in mylist:
    f.write(line + '\n')
f.close()



7.
while True:
        try:
                fname = input("입력 파일 이름: ").strip()
                infile = open(fname, "r") 
                break
        except IOError:
                print("파일 " + fname + " 이 없습니다. 다시 입력하시오.")

print("파일이 성공적으로 열렸습니다.")
infile.close() 


9.
infilename = input("파일 이름을 입력하시오: ").strip()
infile = open(infilename, "r")
file_s = infile.read() 
removed_s = input("삭제할 문자열을 입력하시오: ").strip()
modified_s = file_s.replace(removed_s, "")

infile.close()  
outfile = open(infilename, "w")

print(modified_s, file = outfile, end = "") 
print("변경된 파일이 저장되었습니다.") 
outfile.close() 


11.
##
# 이 프로그램은 파일의 각 줄의 앞에 번호를 붙인다. 
#

infile  = open("proverbs.txt")
outfile = open("output.txt","w")

i = 1

for line in infile:
    outfile.write(str(i) + ": " + line)
    i = i + 1

infile.close()
outfile.close()

 

댓글