python中各种常见文件的读写操作与类型转换详细指南

2025-04-20 16:50

本文主要是介绍python中各种常见文件的读写操作与类型转换详细指南,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

《python中各种常见文件的读写操作与类型转换详细指南》这篇文章主要为大家详细介绍了python中各种常见文件(txt,xls,csv,sql,二进制文件)的读写操作与类型转换,感兴趣的小伙伴可以跟...

1.文件txt读写标准用法

1.1写入文件

要读取文件,首先得使用 open() 函数打开文件。

file = open(file_path, mode='r', encoding=None)

file_path:文件的路径,可以是绝对路径或者相对路径。

mode:文件打开模式,'r' 代表以只读模式打开文件,这是默认值,‘w’表示写入模式。

encoding:文件的编码格式,像 'utf-8'、'gbk' 等,默认值是 None。

下面写入文件的示例:

#写入文件,当open(file_name,'w')时清除文件内容写入新内容,当open(file_name,'a')时直接在文件结尾加入新内容
file_name = 'text.txt'
try:
    with open(file_name,'w',encoding='utf-8') as file:
        file.write("你好!我是老叶爱吃鱼")
        file.write("\n你好呀,老叶,很高兴认识你")
except Exception as e:
    print(f'出错{e}')

系统会判断时候会有text.txt文件,没有的话会创建文件,加入写入内容,示例如下

python中各种常见文件的读写操作与类型转换详细指南

1.2读取文件

下面是读取文件示例:

#读取文件
try:
    with open(file_name,'r',encoding='utf-8') as file:
        print(file.read())
except Exception as e:
    print(f'出错时输出{e}')
#打印出:你好!我是老叶爱吃鱼     你好呀,老叶,很高兴认识你

1.2.1 readline() 方法

readline() 方法每次读取文件的一行内容,返回一个字符串。

# 打开文件
file = open('example.txt', 'r', encoding='utf-8')
# android读取第一行
line = file.readline()
while line:
    print(line.strip())  # strip() 方法用于去除行尾的换行符
    line = file.readline()
# 关闭文件
file.close()

1.2.2 readlines() 方法

readlines() 方法会读取文件的所有行,并将每行内容作为一个元素存储在列表中返回。

# 打开文件
file = open('example.txt', 'r', encoding='utf-8')
# 读取所有行
lines = file.readlines()
for line in lines:
    print(line.strip())
# 关闭文件
file.close()

1.2.3 迭代文件对象

可以直接对文件对象进行迭代,每次迭代会返回文件的一行内容。

# 打开文件
file = open('example.txt', 'r', encoding='utf-8')
# 迭代文件对象
for line in file:
    print(line.strip())
# 关闭文件
file.close()

2. 二进制文件读取

若要读取二进制文件,需将 mode 参数设置为 'rb'。

# 以二进制只读模式打开文件
with open('example.jpg', 'rb') as file:
    # 读取文件全部内容
    content = file.read()
    # 可以对二进制数据进行处理,如保存到另一个文件
    with open('copy.jpg', 'wb') as copy_file:
        copy_file.write(content)

3. 大文件读取

对于大文件,不建议使用 read() 方法一次性读取全部内容,因为这可能会导致内存不足。可以采用逐行读取或者分块读取的方式。

3.1 逐行读取

# 逐行读取大文件
with open('large_file.twww.chinasem.cnxt', 'r', encoding='utf-8') as file:
    for line in file:
        # 处理每行内容
        print(line.strip())

3.2 分块读取

# 分块读取大文件
chunk_size = 1024  # 每次读取 1024 字节
with open('large_file.txt', 'r', encoding='utf-8') as file:
    while True:
        chunk = file.read(chunk_size)
        if not chunk:
            break
        # 处理每个数据块
        print(chunk)

4.Excel表格文件的读写

4.1读取excel

import xlrd
import xlwt
from datetime import date,datetime
 
 
# 打开文件
workbook = xlrd.open_workbook(r"D:\python_file\request_files\excelfile.xlsx", formatting_info=False)
# 获取所有的sheet
print("所有的工作表:",workbook.sheet_names())
sheet1 = workbook.sheet_names()[0]
 
# 根据sheet索引或者名称获取sheet内容
sheet1 = workbook.sheet_by_index(0)
sheet1 = workbook.sheet_by_name("Sheet1")
 
# 打印出所有合并的单元格
print(sheet1.merged_cells)
for (row,row_range,col,col_range) in sheet1.merged_cells:
    print(sheet1.cell_value(row,col))
 
# sheet1的名称、行数、列数
print("工作表名称:%s,行数:%d,列数:%d" % (sheet1.name, sheet1.nrows, sheet1.ncols))
 
# 获取整行和整列的值
row = sheet1.row_values(1)
col = sheet1.col_values(4)
print("第2行的值:%s" % row)
print("第5列的值:%s" % col)
 
# 获取单元格的内容
print("第一行第一列:%s" % sheet1.cell(0,0).value)
print("第一行第二列:%s" % sheet1.cell_value(0,1))
print("第一行第三列:%s" % sheet1.row(0)[2])
 
# 获取单元格内容的数据类型
# 类型 0 empty,1 string, 2 number, 3 date, 4 boolean, 5 error
print("第二行第三列的数据类型:%s" % sheet1.cell(3,2).ctype)
 
# 判断ctype类型是否等于data,如果等于,则用时间格式处理
if sheet1.cell(3,2).ctype == 3:
    data_value = xlrd.xldate_as_tuple(sheet1.cell_value(3, 2),workbook.datemode)
    print(data_value)
    print(date(*data_value[:3]))
    print(date(*data_value[:3]).strftime("%Y\%m\%d"))

4.2 设置单元格样式

style = xlwt.XFStyle()    # 初始化样式
font = xlwt.Font()    # 为样式创建字体
font.name = name    # 设置字体名字对应系统内字体
font.bold = bold    # 是否加粗
font.color_index = 5    # 设置字体颜色
font.height = height    # 设置字体大小
 
# 设置边框的大小
borders = xlwt.Borders()
borders.left = 6
borders.right = 6
borders.top = 6
borders.bottom = 6
 
style.font = font    # 为样式设置字体
style.borders = borders
 
return style

4.3写入excel

writeexcel = xlwt.Workbook()    # 创建工作表
sheet1 = writeexcel.add_sheet(u"Sheet1", cell_overwrite_ok = True)    # 创建sheet
 
row0 = ["编号", "姓名", "性别", "年龄", "生日", "学历"]
num = [1, 2, 3, 4, 5, 6, 7, 8]
column0 = ["a1", "a2", "a3", "a4", "a5", "a6", "a7", "a8"]
education = ["小学", "初中", "高中", "大学"]
 
# 生成合并单元格
i,j = 1,0
while i < 2*len(education) and j < len(education):
    sheet1.write_merge(i, i+1, 5, 5, education[j], set_style("Arial", 200, True))
    i += 2
    j += 1
 
# 生成第一行
for i in range(0, 6):
    sheet1.write(0, i, row0[i])
 
# 生成前两列
for i in range(1, 9):
    sheet1.write(i, 0, i)
    sheet1.write(i, 1, "a1")
 
# 添加超链接
n = "HYperlINK"
sheet1.write_merge(9,9,0,5,xlwt.Formula(n + '("https://www.baidu.com")'))
 
# 保存文件
writeexcel.save("demo.xls")

5.cvs文件的读写操作

5.1读取cvs文件

# 读取 CSV 文件
def read_from_csv(file_path):
    try:
        with open(file_path, 'r', encoding='utf-8') as csvfile:
            reader = csv.reader(csvfile)
            print("读取到的 CSV 文件内容如下:")
            for row in reader:
                print(row)
    except FileNotFoundError:
        print(f"错误: 文件 {file_path} 未找到!")
    except Exception as e:
        print(f"读取文件时出错: {e}")
 

5.2写入cvs文件

# 写入 CSV 文件
def write_to_csv(file_path, data):
    try:
        with open(file_path, 'w', newline='', encoding='utf-8') as csvfile:
            writer = csv.writer(csvfile)
            # 写入表头
            writer.writjserow(['Name', 'Age', 'City'])
            # 写入数据行
            for row in data:
                writer.writerow(row)
        print(f"数据已成功写入 {file_path}")
    except Exception as e:
        print(f"写入文件时出错: {e}")

6.SQL文件读取

import SQLite3
import pandas as pd
 
# 连接到SQLite数据库
conn = sqlite3.connect('example.db')
 
# 读取数据库表
query = "SELECT * FROM table_name"
data = pd.read_sql(query, conn)
print(data.head())
 
# 关闭连接
conn.close()

7.cvs、xls、txt文件相互转换

一般情况下python只会对cvs文件进行数据处理,那么对于很多文件属于二进制文件不能直接处理,那么需要将二进制转为cvs文件后才能处理,如xls是二进制文件需要对xls文件转为cvs文件,操作数据后再转成xls文件即可

7.1xls文件转cvs文件

import pandas as pd
 
def xls_to_csv(xls_file_path, csv_file_path):
    try:
        df = pd.read_excel(xls_file_path)
        df.to_csv(csv_file_path, index=False)
        print(f"成功将 {xls_file_path} 转换为 {csv_file_path}")
    except Exception as e:
        print(f"转换过程中出现错误: {e}")
 
# 示例调用
xls_file = 'example.xls'
csv_file = 'example.csv'
xls_to_csv(xls_file, csv_file)

7.2cvs文件转xls文件

import pandas as pd
 
def csv_to_xls(csv_file_path, xls_file_pjavascriptath):
    try:
        df = pd.read_csv(csv_file_path)
        df.to_excel(xls_file_path, index=False)
        print(f"成功将 {csv_file_path} 转换为 {xls_file_path}")
    except Exception as e:
        print(f"转换过程中出现错误: {e}")
 
# 示例调用
csv_file = 'example.csv'
xls_file = 'example.xls'
csv_to_xls(csv_file, xls_file)

7.3txt文件转cvs文件

import pandas as pd
 
def txt_to_csv(txt_file_path, csv_file_path):
    try:
        # 假设 txt 文件以空格分隔,根据实际情况修改 sep 参数
        df = pd.read_csv(txt_file_path, sep=' ', header=None)
        df.to_csv(csv_file_path, index=False, header=False)
        print(f"成功将 {txt_file_path} 转换为 {csv_file_path}")
    except Exception as e:
        print(f"转换过程中出现错误: {e}")
 
# 示例调用
txt_file = 'example.txt'
csv_file = 'example.csv'
txt_to_csv(txt_file, csv_file)

7.4csv文件转txt文件

import pandas as pd
 
def csv_to_txt(csv_file_path, txt_file_path):
    try:
        df = pd.read_csv(csv_file_path)
        df.to_csv(txt_file_path, sep=' ', index=False, header=False)
        print(f"成功将 {csv_file_path} 转换为 {txt_file_path}")
    except Exception as e:
        print(f"转换过程中出现错误: {e}")
 
# 示例调用
csv_file = 'example.csv'
txt_file = 'example.txt'
csv_to_txt(csv_file, txt_file)

以上就是python中各种常见文件的读写操作与类型转换详细指南的详细内容,更多关于python文件读写与类型转换的资料请关注China编程(www.chinasem.cn)其它相关文章!

这篇关于python中各种常见文件的读写操作与类型转换详细指南的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1154300

相关文章

python常见环境管理工具超全解析

《python常见环境管理工具超全解析》在Python开发中,管理多个项目及其依赖项通常是一个挑战,下面:本文主要介绍python常见环境管理工具的相关资料,文中通过代码介绍的非常详细,需要的朋友... 目录1. conda2. pip3. uvuv 工具自动创建和管理环境的特点4. setup.py5.

Python常用命令提示符使用方法详解

《Python常用命令提示符使用方法详解》在学习python的过程中,我们需要用到命令提示符(CMD)进行环境的配置,:本文主要介绍Python常用命令提示符使用方法的相关资料,文中通过代码介绍的... 目录一、python环境基础命令【Windows】1、检查Python是否安装2、 查看Python的安

SQL Server数据库死锁处理超详细攻略

《SQLServer数据库死锁处理超详细攻略》SQLServer作为主流数据库管理系统,在高并发场景下可能面临死锁问题,影响系统性能和稳定性,这篇文章主要给大家介绍了关于SQLServer数据库死... 目录一、引言二、查询 Sqlserver 中造成死锁的 SPID三、用内置函数查询执行信息1. sp_w

Python UV安装、升级、卸载详细步骤记录

《PythonUV安装、升级、卸载详细步骤记录》:本文主要介绍PythonUV安装、升级、卸载的详细步骤,uv是Astral推出的下一代Python包与项目管理器,主打单一可执行文件、极致性能... 目录安装检查升级设置自动补全卸载UV 命令总结 官方文档详见:https://docs.astral.sh/

Python并行处理实战之如何使用ProcessPoolExecutor加速计算

《Python并行处理实战之如何使用ProcessPoolExecutor加速计算》Python提供了多种并行处理的方式,其中concurrent.futures模块的ProcessPoolExecu... 目录简介完整代码示例代码解释1. 导入必要的模块2. 定义处理函数3. 主函数4. 生成数字列表5.

Python中help()和dir()函数的使用

《Python中help()和dir()函数的使用》我们经常需要查看某个对象(如模块、类、函数等)的属性和方法,Python提供了两个内置函数help()和dir(),它们可以帮助我们快速了解代... 目录1. 引言2. help() 函数2.1 作用2.2 使用方法2.3 示例(1) 查看内置函数的帮助(

Python虚拟环境与Conda使用指南分享

《Python虚拟环境与Conda使用指南分享》:本文主要介绍Python虚拟环境与Conda使用指南,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、python 虚拟环境概述1.1 什么是虚拟环境1.2 为什么需要虚拟环境二、Python 内置的虚拟环境工具

Python实例题之pygame开发打飞机游戏实例代码

《Python实例题之pygame开发打飞机游戏实例代码》对于python的学习者,能够写出一个飞机大战的程序代码,是不是感觉到非常的开心,:本文主要介绍Python实例题之pygame开发打飞机... 目录题目pygame-aircraft-game使用 Pygame 开发的打飞机游戏脚本代码解释初始化部

Python pip下载包及所有依赖到指定文件夹的步骤说明

《Pythonpip下载包及所有依赖到指定文件夹的步骤说明》为了方便开发和部署,我们常常需要将Python项目所依赖的第三方包导出到本地文件夹中,:本文主要介绍Pythonpip下载包及所有依... 目录步骤说明命令格式示例参数说明离线安装方法注意事项总结要使用pip下载包及其所有依赖到指定文件夹,请按照以

Python实现精准提取 PDF中的文本,表格与图片

《Python实现精准提取PDF中的文本,表格与图片》在实际的系统开发中,处理PDF文件不仅限于读取整页文本,还有提取文档中的表格数据,图片或特定区域的内容,下面我们来看看如何使用Python实... 目录安装 python 库提取 PDF 文本内容:获取整页文本与指定区域内容获取页面上的所有文本内容获取