티스토리 뷰

파일입출력


open (name, option) 에서의 option 은 6가지가 있다. 

 option

 Read or Write

 Seek 

 파일이 존재하지 않을 경우 생성여부

 r

 R 

 0

X

 r+

 R/W

 0

X

 w

 W

 0

O

 w+

 R/W

 0

O

 a

 W

 EOF

O

 a+

 R/W

 EOF

O



쓰기

fw = open('test.txt', 'w')
fw.write('These are python tutorials for beginner\n')
fw.write('I like it\n')
fw.close()


읽기

fr = open('test.txt', 'r')
line = fr.readline()
print(line) # -> These are python tutorials for beginner

fr.seek(0)
sentences = fr.read()
print(sentences) # -> These are python tutorials for beginner\n I like it

fr.close()




이미지 다운로드

import urllib.request


def download_image(url):
file_name = 'image.jpg'
urllib.request.urlretrieve(url, file_name)

download_image('http://shofar-music.com/files/cache/thumbnails/711/024/550x500.ratio.jpg')




파일 다운로드

import urllib.request

csv_file_url = 'http://samplecsvs.s3.amazonaws.com/SacramentocrimeJanuary2006.csv'


def download_csv_file(url):
response = urllib.request.urlopen(url);
csv = response.read()
str_csv = str(csv)

lines = str_csv.split('\\n')
file_name = 'csv_test.csv'

fx = open(file_name, 'w')

for line in lines:
fx.write(line + '\n')
fx.close()


download_csv_file(csv_file_url)




출처

http://creativeworks.tistory.com/m/category/Programming/Python%20Tutorials 의 21 ~ 23장 

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함