기타 개발/Python
[Python3] 파일 입출력과 이미지(파일) 다운로드
beankhan
2017. 2. 22. 00:37
파일입출력
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장