Jun's Blog

간단한 기능 구현해보기(파일 입출력) - (5) 본문

Python

간단한 기능 구현해보기(파일 입출력) - (5)

luckydadit 2025. 3. 5. 17:00

1. 파일에 저장하기

print('파일에 기록합니다.')
filename = 'mem.txt'
myfile01 = open(file='mem.txt', mode='wt', encoding='UTF-8')
print(type(myfile01))

# mem.txt 파일에 기록
members = ['홍영식','김민수','박진철','강호숙']
for man in members:
    message = f'\'{man}\'님 안녕하세요.\n'
    myfile01.write(message)
# end for



myfile01.close()
print(f'{filename} 파일이 생성됨')

 

<실행결과>

 

 

print('기존 파일에 내용을 추가합니다.') # at = append text
myfile02 = open(file=filename, mode='at', encoding='UTF-8')

# 홀수 번째 고객님과 짝수 번째 고객님에 대한 멘트를 다르게 적용해 보기
for idx in range(len(members)):
    if idx % 2 == 0:
        message = f'{idx}번째 고객 {members[idx]}님 방가워요\n'
    else:
        message = f'{idx}번째 고객 {members[idx]}님 어서오세요\n'
    # end if

    myfile02.write(message)
# end for

myfile02.close()

 

<실행결과>

 

1.1 여러 파일에 생성 및 저장하기

print('반복문을 사용하여 파일을 여러개 만들어 봅니다.')
print('파일 이름 : somefile01.txt ~ somefile10.txt')
for idx in range(1, 11):
    filename = 'somefile' + str(idx).zfill(2) + '.txt'
    #print(filename)
    myfile = open(file=filename, mode='wt', encoding='UTF-8')
    myfile.write(f'나는 "{filename}" 파일입니다.\n')
    myfile.close()
# end for

 

<실행결과>

 

다음 이름을 사용하여 파일로 만들어 보세요.
'김행운','이행운','최행운','조행운'
print('다음 이름을 사용하여 파일로 만들어 보세요.')
# 예시 : '김행운.txt', '이행운.txt' 등등
members = ['김행운','이행운','최행운','조행운']
for idx in members:
    filename = str(idx) + '.txt'
    myfile = open(file=filename, mode='wt', encoding='UTF-8')
    myfile.write(f'나는 "{filename}" 파일입니다.\n')
    myfile.close()
# end for

 

<실행결과>

 

print('\nwith 구문을 사용하면, close() 함수를 사용하지 않아도 자동으로 closing 동작을 수행합니다.')
with open(file='test.txt', mode='wt', encoding='UTF-8') as testfile:
    testfile.write('가나다\n')
    testfile.write('abc\n')
    testfile.write('123\n')

    # file 매개 변수를 변경하여 testfile 파일에 출력하겠습니다.
    print('hello~', file=testfile)
# end with

print('finished')

 

<참고 내용>

 

<실행결과>

 

 

2. 파일을 읽어오기

 

읽어올 파일 생성하기(Score.txt)

A,60.0,70.0,80.0,F
B,50.0,70.0,100.0,M
C,60.0,70.0,80.0,m
D,40.0,80.0,50.0,F

 

encoding = 'UTF-8'
# 읽어올 파일
source = open(file='Score.txt', mode='rt', encoding=encoding)

# 신규 생성할 파일
destination = open(file='result.txt', mode='wt', encoding=encoding)


data = source.readlines()
print(data)

source.close()
destination.close()

 

<실행결과>

 

encoding = 'UTF-8'
# 읽어올 파일
source = open(file='Score.txt', mode='rt', encoding=encoding)

# 신규 생성할 파일
destination = open(file='result.txt', mode='wt', encoding=encoding)


data = [item.strip() for item in source.readlines()]
print(data)

for bean in data:
    some = bean.split(',')
    print(some)
# end for

source.close()
destination.close()

 

<실행결과>

 

encoding = 'UTF-8'
# 읽어올 파일
source = open(file='Score.txt', mode='rt', encoding=encoding)

# 신규 생성할 파일
destination = open(file='result.txt', mode='wt', encoding=encoding)


data = [item.strip() for item in source.readlines()]
print(data)

for bean in data:
    some = bean.split(',')
    #print(some)

    name = some[0]
    kor = float(some[1])
    eng = float(some[2])
    math = float(some[3])
    gender = some[4]

    total = kor + eng + math
    print(total)
# end for

source.close()
destination.close()

 

<실행결과>

 

encoding = 'UTF-8'
# 읽어올 파일
source = open(file='Score.txt', mode='rt', encoding=encoding)

# 신규 생성할 파일
destination = open(file='result.txt', mode='wt', encoding=encoding)


data = [item.strip() for item in source.readlines()]
print(data)

for bean in data:
    some = bean.split(',')
    #print(some)

    name = some[0]
    kor = float(some[1])
    eng = float(some[2])
    math = float(some[3])
    _gender = some[4].upper()

    total = kor + eng + math
    average = total / 3.0

    if _gender == 'M': #or _gender == 'm':
        gender = '남자'
    else:
        gender = '여자'
    # end if

    # '이름/성별/총점/평균' 형식
    sentences = '%s/%s/%.1f/%.2f\n' % (name, gender, total, average)
    print(sentences)

    destination.write(sentences)

# end for

source.close()
destination.close()
print('finished')

 

<실행결과>