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)
全栈程序员-站长的头像全栈程序员-站长

相关推荐

  • vue3数据劫持_vue实现keepalive

    vue3数据劫持_vue实现keepalive模仿vue的数据劫持,实现mvvm

    2022年4月22日
  • pycharm运行结果区显示乱码_windows控制台乱码

    pycharm运行结果区显示乱码_windows控制台乱码解决pycharmTerminal(控制台)乱码问题描述解决方法问题描述环境:ubuntu18.04系统终端:zsh(使用onmyzsh美化过)pycharm2020.3.2解决方法乱码原因还是字体支持的问题,相近的问题见文章ubuntu美化及解决使用zsh后无法运行ROS中的安装PowerLine字体打开pycharm的setting(File->Settings)定位到Editor|ColorScheme|ConsoleFont,修改设

    2022年11月1日
  • js layui 弹出子窗体_Layui弹出层 加载 做编辑页面的方法[通俗易懂]

    js layui 弹出子窗体_Layui弹出层 加载 做编辑页面的方法[通俗易懂]layui是一款优秀的模块化前端框架。利用layui弹出层做编辑页面先上效果图基本准备,引入layui的layui.css,layui.js文件Js方法/***页面内弹出编辑窗口//需要引入layui.jslayui.css文件*@param{}title标题不显示为false*@param{}area大小[“400px”,”500px”]或者”400px”—&…

    2022年5月16日
  • 太平洋网络ip地址查询接口使用,返回json格式,默认返回jsonp

    太平洋网络ip地址查询接口使用,返回json格式,默认返回jsonp

    2021年11月5日
  • java面向对象三大特性「建议收藏」

    java面向对象三大特性「建议收藏」一、面向对象的概念面向对象是一种符合人类思维习惯的编程思想。现实生活中存在各种形态不同的事物,这些事物之间存在着各种各样的联系。在程序中使用对象来映射现实中的事物使用对象的关系来描述事物之间的联系,这种思想就是面向对象。提到面向对象,自然会想到面向过程,面向过程就是分析解决问题所需要的步骤,然后用函数把这些步骤一一实现,使用的时候一个一个依次调用就可以了。面向对象则是把解决的问题按照一定规则划分为多个独立的对象,然后通过调用对象的方法来解决问题。当然,一个应用程序会包含多个对象,通过多个对象的相互配合来

    2022年7月8日
  • Linux下ARM开发环境搭建

    Linux下ARM开发环境搭建本人的系统环境:Linuxubuntu3.8.0-35-generic#50-UbuntuSMPTueDec301:25:33UTC2013i686i686i686GNU/Linux1、安装skyeyesudoapt-getinstallskyeyeskyeye-h可以看到skyeye的版本号为1.2.5也可以到http

    2022年5月8日

发表回复

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

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