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

Posted zl666

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python第三周之文件的读写以及简单的爬虫介绍相关的知识,希望对你有一定的参考价值。

文件的读写

  读

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第三周之文件的读写以及简单的爬虫介绍的主要内容,如果未能解决你的问题,请参考以下文章

简单介绍python编程之文件读写

python系统学习:第三周之简单的三级菜单

python系统学习:第三周之文件操作

Python作业工资管理系统(第三周)

Python爬虫之Scrapy框架系列——创建并运行你的第一个Scrapy demo项目

Python爬虫之Scrapy框架系列——创建并运行你的第一个Scrapy demo项目