python保存文件的几种方式「建议收藏」

python保存文件的几种方式「建议收藏」当我们获取到一些数据时,例如使用爬虫将网上的数据抓取下来时,应该怎么把数据保存为不同格式的文件呢?下面会分别介绍用python保存为txt、csv、excel甚至保存到mongodb数据库中文件的方法。保存为txt文件首先我们模拟数据是使用爬虫抓取下来的,抓取的下来的数据大致就是这样的下面使用代码保存为txt文件importrequestsfromlxmlimportetr…

大家好,又见面了,我是你们的朋友全栈君。

当我们获取到一些数据时,例如使用爬虫将网上的数据抓取下来时,应该怎么把数据保存为不同格式的文件呢?下面会分别介绍用python保存为 txt、csv、excel甚至保存到mongodb数据库中文件的方法

保存为txt文件

首先我们模拟数据是使用爬虫抓取下来的, 抓取的下来的数据大致就是这样的
在这里插入图片描述
下面使用代码保存为txt文件

import requests
from lxml import etree


url = 'https://ke.qq.com/course/list/?mt=1001'
headers = { 
   "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
                         "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36"}
# 获取放回的html源代码字符串
response = requests.get(url, headers=headers).text


def save_txt():  # 保存为txt文件
    f = open("./ke.txt", "w", encoding="utf8")
    # 抓取文章目录和标题
    html = etree.HTML(response)
    li_list = html.xpath('//ul[@class="course-card-list"]/li')
    for li in li_list:
        title = li.xpath('.//a[@class="item-tt-link"]/@title')[0]
        href = li.xpath('.//a[@class="item-tt-link"]/@href')[0]
        href = "https:" + href
        f.write(f'{title}-->{href}\n')
    f.close()
save_txt()

运行程序,效果图如下
在这里插入图片描述

保存为csv文件格式

代码如下

import requests
from lxml import etree
import csv

url = 'https://ke.qq.com/course/list/?mt=1001'
headers = { 
   "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
                         "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36"}
# 获取放回的html源代码字符串
response = requests.get(url, headers=headers).text

def save_csv():  # 保存为csv文件
    with open("ke.csv", "w", encoding="utf8", newline='') as f:
        header = ["title", "href"]
        writer = csv.DictWriter(f, header)  # 创建字典writer
        writer.writeheader()
        # 抓取文章目录和标题
        html = etree.HTML(response)
        li_list = html.xpath('//ul[@class="course-card-list"]/li')
        for i, li in enumerate(li_list):  # 获取索引和值
            title = li.xpath('.//a[@class="item-tt-link"]/@title')[0]
            href = li.xpath('.//a[@class="item-tt-link"]/@href')[0]
            href = "https:" + href
            item = { 
   "title": title, "href": href}
            print(item)
            writer.writerow(item)
        print("保存成功...")

save_csv()

运行程序,文件会存储再当前目录下。
在这里插入图片描述

存储为excel文件

代码如下:

import requests
from lxml import etree
import openpyxl

url = 'https://ke.qq.com/course/list/?mt=1001'
headers = { 
   "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
                         "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36"}
# 获取放回的html源代码字符串
response = requests.get(url, headers=headers).text
def save_excel():  # 保存为excel文件
    wb = openpyxl.Workbook()  # 创建工作铺
    ws = wb.active  # 创建工作表
    # 写入表头
    ws["A1"] = "课程标题"
    ws["B1"] = "课堂链接"

    # 抓取文章目录和标题
    html = etree.HTML(response)
    li_list = html.xpath('//ul[@class="course-card-list"]/li')
    for i, li in enumerate(li_list):  # 获取索引和值
        title = li.xpath('.//a[@class="item-tt-link"]/@title')[0]
        href = li.xpath('.//a[@class="item-tt-link"]/@href')[0]
        href = "https:" + href
        ws.cell(row=i+2, column=1, value=title)  # 写入行,列所对应的值
        ws.cell(row=i+2, column=2, value=href)
    wb.save("./QQ课堂.xlsx")


save_excel()

运行程序,打开文件
在这里插入图片描述

保存在mongodb数据库中

代码如下

import requests
import pymongo
from lxml import etree
def save_mongo():  # 将数据存储到monggodb数据库
    client = pymongo.MongoClient()  # 连接数据库
    db = client["ke"]  # 创建数据库
    collection = db["ke_content"]
    items = []
    html = etree.HTML(response)
    li_list = html.xpath('//ul[@class="course-card-list"]/li')
    for i, li in enumerate(li_list):  # 获取索引和值
        title = li.xpath('.//a[@class="item-tt-link"]/@title')[0]
        href = li.xpath('.//a[@class="item-tt-link"]/@href')[0]
        href = "https:" + href
        item = { 
   "title": title, "href": href}
        items.append(item)  # 将每个item添加到items列表中
    collection.insert_many(items)  # 插入多条数据
    for content in collection.find():  # 查看数据库中的数据
        print(content)

运行代码,可以在终端中查看数据库中的内容
在这里插入图片描述
也可以直接进入数据库中查看,打开终端,进入数据库。查看即可
在这里插入图片描述

小结

最后把所有代码整理一遍,大家只需要按需所用即可,只需要修改部分代码就好了。

import pymongo
import requests
from lxml import etree
import openpyxl  # 保存为excel文件
import csv  # 保存为csv文件


url = 'https://ke.qq.com/course/list/?mt=1001'
headers = { 
   "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
                         "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36"}
# 获取放回的html源代码字符串
response = requests.get(url, headers=headers).text


def save_txt():  # 保存为txt文件
    f = open("./ke.txt", "w", encoding="utf8")
    # 抓取文章目录和标题
    html = etree.HTML(response)
    li_list = html.xpath('//ul[@class="course-card-list"]/li')
    for li in li_list:
        title = li.xpath('.//a[@class="item-tt-link"]/@title')[0]
        href = li.xpath('.//a[@class="item-tt-link"]/@href')[0]
        href = "https:" + href
        f.write(f'{title}-->{href}\n')
    f.close()


def save_csv():  # 保存为csv文件
    with open("ke.csv", "w", encoding="utf8", newline='') as f:
        header = ["title", "href"]
        writer = csv.DictWriter(f, header)
        writer.writeheader()
        # 抓取文章目录和标题
        html = etree.HTML(response)
        li_list = html.xpath('//ul[@class="course-card-list"]/li')
        for i, li in enumerate(li_list):  # 获取索引和值
            title = li.xpath('.//a[@class="item-tt-link"]/@title')[0]
            href = li.xpath('.//a[@class="item-tt-link"]/@href')[0]
            href = "https:" + href
            item = { 
   "title": title, "href": href}
            print(item)
            writer.writerow(item)
        print("保存成功...")


def save_excel():  # 保存为excel文件
    wb = openpyxl.Workbook()  # 创建工作铺
    ws = wb.active  # 创建工作表
    # 写入表头
    ws["A1"] = "课程标题"
    ws["B1"] = "课堂链接"

    # 抓取文章目录和标题
    html = etree.HTML(response)
    li_list = html.xpath('//ul[@class="course-card-list"]/li')
    for i, li in enumerate(li_list):  # 获取索引和值
        title = li.xpath('.//a[@class="item-tt-link"]/@title')[0]
        href = li.xpath('.//a[@class="item-tt-link"]/@href')[0]
        href = "https:" + href
        ws.cell(row=i+2, column=1, value=title)  # 写入行,列所对应的值
        ws.cell(row=i+2, column=2, value=href)
    wb.save("./QQ课堂.xlsx")

    print("保存成功")


def save_mongo():  # 将数据存储到monggodb数据库
    client = pymongo.MongoClient()  # 连接数据库
    db = client["ke"]  # 创建数据库
    collection = db["ke_content"]
    items = []
    html = etree.HTML(response)
    li_list = html.xpath('//ul[@class="course-card-list"]/li')
    for i, li in enumerate(li_list):  # 获取索引和值
        title = li.xpath('.//a[@class="item-tt-link"]/@title')[0]
        href = li.xpath('.//a[@class="item-tt-link"]/@href')[0]
        href = "https:" + href
        item = { 
   "title": title, "href": href}
        items.append(item)
    collection.insert_many(items)  # 插入多条数据
    for content in collection.find():  # 遍历在这个集合中的数据
        print(content)


if __name__ == '__main__':
    save_mongo()  # 调用相应的方法即可

如果有什么不足之处请指出,我会加以改进,共同进步!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/125042.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • 100个javaweb实战项目(视频+源码+文档),带你上天![通俗易懂]

    所有项目的链接均为永久有效,但也不免出现个别链接被和谐的情况,如有链接失效,请及时留言,相遇即是缘分,请收藏此文,下次见面不迷路!话不多说,直接来干货!第01项目:SSM大型互联网电商项目(视频+源码)链接:https://pan.baidu.com/s/1VgNuaZ8pDpWHtBfEe7_28Q提取码:7zei第02项目:SSM分布式互联网商城(视频+文档资料)链接:https://pan.baidu.com/s/1SxNVzQcJNHisHUmj66xlMQ提取码:1n.

    2022年4月16日
    706
  • 三巨头是什么意思(腾讯财报)

    5月22日晚间,拼多多与阿里巴巴相继公布了财报,拼多多一季度营收同比增长44%,阿里营收则同比增22%,都好于市场预期。而从电商业务来看,阿里虽一直领先于京东与后来者拼多多,但由于家大业大,业务链分散,使得另外两家有了后来居上的机会,拼多多今天的财报中提及了其年度活跃用户已达到了6.28亿,京东近期也在物流方面频频发力,并在上周交出了一季度亮眼的财报,这使…

    2022年4月16日
    72
  • 电子设备日常使用总结

    电子设备日常使用总结

    2021年5月17日
    122
  • map怎么转json对象_json怎么获取map

    map怎么转json对象_json怎么获取map如何把JSON对象转为map对象呢?JSON对象保存在大括号内。就像在JavaScript中,对象可以保存多个键/值对。Map对象保存键/值对,是键/值对的集合。任何值(对象或者原始值)都可以作为一个键或一个值。Object结构提供了“字符串—值”的对应,Map结构提供了“值—值”的对应。javascript将JSON对象转为map对象可以利用阿里巴巴封装的FastJSON来转换。有多种…

    2022年8月23日
    7
  • matlab中find函数用法[通俗易懂]

    matlab中find函数用法[通俗易懂]1.返回素有非零元素的位置例如:注:竖着数!!2.条件:find(A==1)例如:返回的仍然是位置!3.返回前N个非零元素的位置,find(A,X)例如:4.返回最后一个非零值的位置find(A,1,‘last’)例如:5.返回最后一个非零值的行列位置或者A中非零元素位置例如:6.[a,b,v]=find(A),找出A中非零元素所在的行和列,分别存储在a和b中,…

    2022年7月17日
    14
  • 说说anchorPoint[通俗易懂]

    说说anchorPoint[通俗易懂]anchorPoint属性是CGPoint(x,y),x,y的取值是按比例取值,一般用0~1,默认是(0.5,0.5),表示图层的position在自身的位置,举个例子,在红色view确定完大小位

    2022年7月3日
    40

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号