首页 > 编程语言 > 详细

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

时间:2018-03-17 14:46:42      阅读:240      评论:0      收藏:0      [点我收藏+]

文件的读写

  读

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第三周之文件的读写以及简单的爬虫介绍

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!