[Python] 10-3장 파일 입출력 응용(행맨, 파일 안의 문자열 삭제, 빈도수 세기 등)

- 파일에서 단어 읽기

infile = open("C:\\Users\\Desktop\\happy.txt", "r")
for line in infile:
    line = line.rstrip()
    word_list = line.split()
    for word in word_list:
        print(word)
infile.close()

 

 

- 파일 복사

infilename = input("기존 파일 이름: ")
outfilename = input("복사된 파일 이름: ")
infile = open(infilename, "r")
outfile = open(outfilename, "w")

s = infile.read()

outfile.write(s)

infile.close()
outfile.close()

 

shutil 모듈 사용
import shutil
shutil.copy("C:\\Users\\Desktop\\happy.txt", "C:\\Users\\Desktop\\copyed.txt")

 

 

- 행맨

import random

guesses = ''
turns = 5

infile = open("C:\\Users\\Desktop\\word.txt", "r")
for line in infile:
    line = line.rstrip()
    word_list = list(line.split())
word = random.choice(word_list)

while turns > 0:
    failed = 0
    for char in word:
        if char in guesses:
            print(char, end="")
        else:
            print("-", end="")
            failed += 1
    if failed == 0:
        print(" 사용자 승리!")
        break
    print("")
    guess = input("단어를 추측하시오: ")
    guesses += guess
    if guess not in word:
        turns -= 1
        print("틀렸습니다.")
        print("{}번의 기회가 남았습니다.".format(turns))
        if turns == 0:
            print("사용자 패배. 정답은 {}입니다.".format(word))
            
infile.close()

 

 

- 파일 안의 글자 수 세기

count = 0
filename = input("파일 이름을 입력하세요: ")
file = open(filename, "r")
for line in file:
    line = line.rstrip()
    word_list = line.split()
    for word in word_list:
        count += len(word)
        
print("파일 안에는 총 {} 개의 글자가 있습니다.".format(count))
file.close()

 

 

- 파일 안의 문자열 삭제

filename = input("파일 이름을 입력하세요: ")
file = open(filename, "r")
file_s = file.read()
string = input("삭제할 문자열을 입력하시오: ").strip()
modified_s = file_s.replace(string, "")
file.close()

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

 

 

- 파일 안의 문자들의 빈도수

filename = input("입력 파일 이름: ")
alpha = {}
file = open(filename, "r")
rfile = file.read()
for line in rfile:
    for ch in line:
        if ch in alpha:
            alpha[ch] += 1
        else:
            alpha[ch] = 1
file.close()
print(alpha)

 

 

- 리스트 파일에 저장

import pickle
lst = [12, 3.14, [1, 2, 3, 4, 5]]
file = open("C:\\Users\\Desktop\\list.p", "wb")
pickle.dump(lst, file)
file.close()
file = open("C:\\Users\\Desktop\\list.p", "rb")
obj = pickle.load(file)
for ob in obj:
    print(ob)
file.close()

 

 

- 파일을 읽어서 합계, 평균 구하기

infilename = input("입력 파일 이름: ")
outfilename = input("출력 파일 이름: ")

infile = open(infilename,"r")
outfile = open(outfilename, "w", encoding="utf-8")
ans = 0
count = 0

for line in infile:
    ans += float(line)
    count += 1

print("합계={}".format(ans), file = outfile)
print("평균={}".format(ans/count), file = outfile)

infile.close()
outfile.close()

 

 

※ 두근두근 파이썬 11장 연습문제 참조