Super Kawaii Cute Cat Kaoani
본문 바로가기
💻 Programming/Python

[Python] csv 파일 입출력

by wonee1 2023. 1. 22.
728x90

csv 파일

💡데이터가 콤마로 구분된 텍스트 파일 형식 
 
 

csv 파일 입출력 
 

csv 파일 쓰기 

import csv

data=[
    ["이름","반","번호"],
    ["재석",1,20],
    ["홍철",3,8],
    ["형돈",5,32]
    
]

file=open("student.csv","w",newline="")
writer=csv.writer(file)

for d in data:
    writer.writerow(d)
    
file.close()

 
 
open 시 newline=""을 적으면 자동줄바꿈이 되지않는다 
 
 
 
 
csv 파일 읽기

import csv

file=open("student.csv","r")
reader=csv.reader(file)
for data in reader:
    print(data)
file.close()

 
 
 
 
 

import csv

def show_profit(data):
    name=data[0] #종목
    purchase_price=int(data[1])#매입가
    amount=int(data[2])#수량
    target_price=int(data[3]) #목표가
    
    profit=(target_price-purchase_price)*amount #수익금
    profit_ratio=(target_price/purchase_price-1)*100  #수익률 

    print(f"{name} {profit} {profit_ratio:.2f}%") 


#파일 열기
file=open("./파일입출력 기본/mystock.csv","r",encoding='UTF-8')   #경로 주의할것 
#인코딩을 넣어줘야함 

#파일 데이터 읽기
reader=list(csv.reader(file))  #reader는 리스트가 아니기때문에 csv를 리스트로 자료형 변환해줘야함 
for data in reader[1:]:
    show_profit(data)
file.close()

 
 
 
 
 
 

728x90

'💻 Programming > Python' 카테고리의 다른 글

[Python] 파이썬 슬라이싱 정리  (0) 2025.04.18
[Python] 클래스 정리  (0) 2023.02.26
[Python] 파일 입출력 기본  (0) 2023.01.22
[Python] 과제 10주차  (0) 2023.01.08
[Python] 과제 9주차  (0) 2023.01.08