zoukankan      html  css  js  c++  java
  • Python第三周之文件的读写以及简单的爬虫介绍

    文件的读写

      读

    import time
    
    
    def main():
        """
        文件的读写,注意open的用法以及,文件地址的输入。
        :return: 
        """
        temp = open('abcd/hello.txt', 'r', encoding='utf-8')   # 打开文件名,r 为读, w 为写。
        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()
  • 相关阅读:
    jQuery 选择器
    使用JQuery获取对象的几种方式
    多层架构+MVC+EF+AUTOFAC+AUTOMAPPER
    ASP.NET 2.0服务器控件开发的基本概念(转载)
    系统构架设计应考虑的因素
    超级面试题
    架构的点滴
    程序员的职业素养---转载
    imovie的快速入门
    实用的设计模式【二】——类的组织
  • 原文地址:https://www.cnblogs.com/zl666/p/8589418.html
Copyright © 2011-2022 走看看