python(17) 파일 다루기

hyukstory 혁스토리·2020년 8월 28일
0

python

목록 보기
23/35

파일 다루기

f = open('python.txt' , "w") # 쓰기모드
for i in range(0, 101) :
    f.write("나는 파이썬을 " + str(i) + "번 좋아했습니다.")
f.close()


f = open('python.txt' , "r") # 읽기 모드
for line in f.readlines() :
    print(line)

f.close()


f = open('python.txt' , "a") # 추가 모드
for i in range(101, 201) :
    f.write("나는 파이썬을 " + str(i) + "번 좋아했습니다.")
f.close()

with 키워드

close() 안해줘도 알아서 닫힘

with open("ch.9.21.txt", "w") as f:  # f = open("ch.9.21.txt", "w")
    f.write("1\n")
    f.write("2\n")
    f.write("3\n")

csv 저장

columns = ["이름", "나이", "주소"]

names = ["철구", "맹구", "짱구", "유리"]
ages = ["20", "21", "20", "22"]
address = ["경기도", "강원도", "경상도", "전라도"]

with open("C:/Users/student/Desktop/python/P_3week/CSVtest.csv", "a") as f:
    column = ','.join(columns) + '\n'
    f.write(column)

    for i in range(0, len(names)):
        row = ('%s, %s, %s\n')%(names[i], ages[i], address[i])
        f.write(row)

이미지 저장

import requests as rq

url = 'https://avatars2.githubusercontent.com/u/12229295?v=4&s=60'

res = rq.get(url)

with open('t.png', 'wb') as f:
    f.write(res.content)

exe 파일 다운 받아서 저장하기

from urllib.request import urlopen

fileurl = "https://chromedriver.storage.googleapis.com/84.0.4147.30/chromedriver_win32.zip"

BUFSIZE = 256*1024 
filename = fileurl.split('/')[-1]

try :
    with urlopen(fileurl) as f:
        with open(filename, 'wb') as h:
            buf = f.read(BUFSIZE)
            while buf :
                h.write(buf)
                buf = f.read(BUFSIZE)
                
except Exception as e:
    print(e)
        
profile
문돌이의 고군분투 개발 공부

0개의 댓글