码迷,mamicode.com
首页 > 编程语言 > 详细

Python第三周之文件的读写以及简单的爬虫介绍

时间:2018-03-17 15:16:34      阅读:199      评论:0      收藏:0      [点我收藏+]

标签:简单   odi   pen   contents   text   图片   log   class   div   

文件的读写

  读

import time


def main():
    """
    文件的读写,注意open的用法以及,文件地址的输入。
    :return: 
    """
    temp = open(abcd/hello.txt, r, encoding=utf-8) 
    contents = temp.readlines()
    for content in contents:
        print(content)
        time.sleep(1)
  temp.close()
if __name__ == __main__: main()

  写

def main():
    try:
        with open(abcd/hello.txt, w, encoding=utf-8) as fs:
            fs.write(奥尼)
    except FileNotFoundError:
        print(无法打开)
    except IOError as e:
        print(e)


if __name__ == __main__:
    main()

读和写

def main():

    try:
        with open(abcd/a.jpg, rb) as fs1:
            date = fs1.read()
        with open(efg/b.jpg, wb) as fs2:
            fs2.write(date)

    except FileNotFoundError:
        print(无法打开)
    except IOError:
        print(读写错误)
    print(程序执行结束)


if __name__ == __main__:
    main()

爬网络上的图片

import json
import requests


def main():
    resp = requests.get(http://api.tianapi.com/nba/?key=81085f5747a59581327b29d1bccfb925&num=10)
    mydict = json.loads(resp.text)
    print(mydict)
    for tempdict in mydict[newslist]:
        pic_url = tempdict[picUrl]
        resp = requests.get(pic_url)
        filename = pic_url[pic_url.rfind(/) + 1:]
        try:
            with open(filename, wb) as fs:
                fs.write(resp.content)
        except IOError as e:
            print(e)


if __name__ == __main__:
    main()

 

Python第三周之文件的读写以及简单的爬虫介绍

标签:简单   odi   pen   contents   text   图片   log   class   div   

原文地址:https://www.cnblogs.com/zl666/p/8589418.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!