• 设为首页
  • 收藏本站
  • 积分充值
  • VIP赞助
  • 手机版
  • 微博
  • 微信
    微信公众号 添加方式:
    1:搜索微信号(888888
    2:扫描左侧二维码
  • 快捷导航
    福建二哥 门户 查看主题

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

    发布者: 404号房间 | 发布时间: 2025-6-14 12:22| 查看数: 66| 评论数: 0|帖子模式

    1.文件txt读写标准用法


    1.1写入文件

    要读取文件,首先得使用 open() 函数打开文件。
    1. file = open(file_path, mode='r', encoding=None)
    复制代码
    file_path:文件的路径,可以是绝对路径或者相对路径。
    mode:文件打开模式,'r' 代表以只读模式打开文件,这是默认值,‘w’表示写入模式。
    encoding:文件的编码格式,像 'utf-8'、'gbk' 等,默认值是 None。
    下面写入文件的示例:
    1. #写入文件,当open(file_name,'w')时清除文件内容写入新内容,当open(file_name,'a')时直接在文件结尾加入新内容
    2. file_name = 'text.txt'
    3. try:
    4.     with open(file_name,'w',encoding='utf-8') as file:
    5.         file.write("你好!我是老叶爱吃鱼")
    6.         file.write("\n你好呀,老叶,很高兴认识你")
    7. except Exception as e:
    8.     print(f'出错{e}')
    复制代码
    系统会判断时候会有text.txt文件,没有的话会创建文件,加入写入内容,示例如下


    1.2读取文件

    下面是读取文件示例:
    1. #读取文件
    2. try:
    3.     with open(file_name,'r',encoding='utf-8') as file:
    4.         print(file.read())
    5. except Exception as e:
    6.     print(f'出错时输出{e}')
    7. #打印出:你好!我是老叶爱吃鱼     你好呀,老叶,很高兴认识你
    复制代码
    1.2.1 readline() 方法
    readline() 方法每次读取文件的一行内容,返回一个字符串。
    1. # 打开文件
    2. file = open('example.txt', 'r', encoding='utf-8')
    3. # 读取第一行
    4. line = file.readline()
    5. while line:
    6.     print(line.strip())  # strip() 方法用于去除行尾的换行符
    7.     line = file.readline()
    8. # 关闭文件
    9. file.close()
    复制代码
    1.2.2 readlines() 方法
    readlines() 方法会读取文件的所有行,并将每行内容作为一个元素存储在列表中返回。
    1. # 打开文件
    2. file = open('example.txt', 'r', encoding='utf-8')
    3. # 读取所有行
    4. lines = file.readlines()
    5. for line in lines:
    6.     print(line.strip())
    7. # 关闭文件
    8. file.close()
    复制代码
    1.2.3 迭代文件对象
    可以直接对文件对象进行迭代,每次迭代会返回文件的一行内容。
    1. # 打开文件
    2. file = open('example.txt', 'r', encoding='utf-8')
    3. # 迭代文件对象
    4. for line in file:
    5.     print(line.strip())
    6. # 关闭文件
    7. file.close()
    复制代码
    2. 二进制文件读取

    若要读取二进制文件,需将 mode 参数设置为 'rb'。
    1. # 以二进制只读模式打开文件
    2. with open('example.jpg', 'rb') as file:
    3.     # 读取文件全部内容
    4.     content = file.read()
    5.     # 可以对二进制数据进行处理,如保存到另一个文件
    6.     with open('copy.jpg', 'wb') as copy_file:
    7.         copy_file.write(content)
    复制代码
    3. 大文件读取

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

    3.1 逐行读取
    1. # 逐行读取大文件
    2. with open('large_file.txt', 'r', encoding='utf-8') as file:
    3.     for line in file:
    4.         # 处理每行内容
    5.         print(line.strip())
    复制代码
    3.2 分块读取
    1. # 分块读取大文件
    2. chunk_size = 1024  # 每次读取 1024 字节
    3. with open('large_file.txt', 'r', encoding='utf-8') as file:
    4.     while True:
    5.         chunk = file.read(chunk_size)
    6.         if not chunk:
    7.             break
    8.         # 处理每个数据块
    9.         print(chunk)
    复制代码
    4.Excel表格文件的读写


    4.1读取excel
    1. import xlrd
    2. import xlwt
    3. from datetime import date,datetime


    4. # 打开文件
    5. workbook = xlrd.open_workbook(r"D:\python_file\request_files\excelfile.xlsx", formatting_info=False)
    6. # 获取所有的sheet
    7. print("所有的工作表:",workbook.sheet_names())
    8. sheet1 = workbook.sheet_names()[0]

    9. # 根据sheet索引或者名称获取sheet内容
    10. sheet1 = workbook.sheet_by_index(0)
    11. sheet1 = workbook.sheet_by_name("Sheet1")

    12. # 打印出所有合并的单元格
    13. print(sheet1.merged_cells)
    14. for (row,row_range,col,col_range) in sheet1.merged_cells:
    15.     print(sheet1.cell_value(row,col))

    16. # sheet1的名称、行数、列数
    17. print("工作表名称:%s,行数:%d,列数:%d" % (sheet1.name, sheet1.nrows, sheet1.ncols))

    18. # 获取整行和整列的值
    19. row = sheet1.row_values(1)
    20. col = sheet1.col_values(4)
    21. print("第2行的值:%s" % row)
    22. print("第5列的值:%s" % col)

    23. # 获取单元格的内容
    24. print("第一行第一列:%s" % sheet1.cell(0,0).value)
    25. print("第一行第二列:%s" % sheet1.cell_value(0,1))
    26. print("第一行第三列:%s" % sheet1.row(0)[2])

    27. # 获取单元格内容的数据类型
    28. # 类型 0 empty,1 string, 2 number, 3 date, 4 boolean, 5 error
    29. print("第二行第三列的数据类型:%s" % sheet1.cell(3,2).ctype)

    30. # 判断ctype类型是否等于data,如果等于,则用时间格式处理
    31. if sheet1.cell(3,2).ctype == 3:
    32.     data_value = xlrd.xldate_as_tuple(sheet1.cell_value(3, 2),workbook.datemode)
    33.     print(data_value)
    34.     print(date(*data_value[:3]))
    35.     print(date(*data_value[:3]).strftime("%Y\%m\%d"))
    复制代码
    4.2 设置单元格样式
    1. style = xlwt.XFStyle()    # 初始化样式
    2. font = xlwt.Font()    # 为样式创建字体
    3. font.name = name    # 设置字体名字对应系统内字体
    4. font.bold = bold    # 是否加粗
    5. font.color_index = 5    # 设置字体颜色
    6. font.height = height    # 设置字体大小

    7. # 设置边框的大小
    8. borders = xlwt.Borders()
    9. borders.left = 6
    10. borders.right = 6
    11. borders.top = 6
    12. borders.bottom = 6

    13. style.font = font    # 为样式设置字体
    14. style.borders = borders

    15. return style
    复制代码
    4.3写入excel
    1. writeexcel = xlwt.Workbook()    # 创建工作表
    2. sheet1 = writeexcel.add_sheet(u"Sheet1", cell_overwrite_ok = True)    # 创建sheet

    3. row0 = ["编号", "姓名", "性别", "年龄", "生日", "学历"]
    4. num = [1, 2, 3, 4, 5, 6, 7, 8]
    5. column0 = ["a1", "a2", "a3", "a4", "a5", "a6", "a7", "a8"]
    6. education = ["小学", "初中", "高中", "大学"]

    7. # 生成合并单元格
    8. i,j = 1,0
    9. while i < 2*len(education) and j < len(education):
    10.     sheet1.write_merge(i, i+1, 5, 5, education[j], set_style("Arial", 200, True))
    11.     i += 2
    12.     j += 1

    13. # 生成第一行
    14. for i in range(0, 6):
    15.     sheet1.write(0, i, row0[i])

    16. # 生成前两列
    17. for i in range(1, 9):
    18.     sheet1.write(i, 0, i)
    19.     sheet1.write(i, 1, "a1")

    20. # 添加超链接
    21. n = "HYPERLINK"
    22. sheet1.write_merge(9,9,0,5,xlwt.Formula(n + '("https://www.baidu.com")'))

    23. # 保存文件
    24. writeexcel.save("demo.xls")
    复制代码
    5.cvs文件的读写操作


    5.1读取cvs文件
    1. # 读取 CSV 文件
    2. def read_from_csv(file_path):
    3.     try:
    4.         with open(file_path, 'r', encoding='utf-8') as csvfile:
    5.             reader = csv.reader(csvfile)
    6.             print("读取到的 CSV 文件内容如下:")
    7.             for row in reader:
    8.                 print(row)
    9.     except FileNotFoundError:
    10.         print(f"错误: 文件 {file_path} 未找到!")
    11.     except Exception as e:
    12.         print(f"读取文件时出错: {e}")
    复制代码
    5.2写入cvs文件
    1. # 写入 CSV 文件
    2. def write_to_csv(file_path, data):
    3.     try:
    4.         with open(file_path, 'w', newline='', encoding='utf-8') as csvfile:
    5.             writer = csv.writer(csvfile)
    6.             # 写入表头
    7.             writer.writerow(['Name', 'Age', 'City'])
    8.             # 写入数据行
    9.             for row in data:
    10.                 writer.writerow(row)
    11.         print(f"数据已成功写入 {file_path}")
    12.     except Exception as e:
    13.         print(f"写入文件时出错: {e}")
    复制代码
    6.SQL文件读取
    1. import sqlite3
    2. import pandas as pd

    3. # 连接到SQLite数据库
    4. conn = sqlite3.connect('example.db')

    5. # 读取数据库表
    6. query = "SELECT * FROM table_name"
    7. data = pd.read_sql(query, conn)
    8. print(data.head())

    9. # 关闭连接
    10. conn.close()
    复制代码
    7.cvs、xls、txt文件相互转换

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

    7.1xls文件转cvs文件
    1. import pandas as pd

    2. def xls_to_csv(xls_file_path, csv_file_path):
    3.     try:
    4.         df = pd.read_excel(xls_file_path)
    5.         df.to_csv(csv_file_path, index=False)
    6.         print(f"成功将 {xls_file_path} 转换为 {csv_file_path}")
    7.     except Exception as e:
    8.         print(f"转换过程中出现错误: {e}")

    9. # 示例调用
    10. xls_file = 'example.xls'
    11. csv_file = 'example.csv'
    12. xls_to_csv(xls_file, csv_file)
    复制代码
    7.2cvs文件转xls文件
    1. import pandas as pd

    2. def csv_to_xls(csv_file_path, xls_file_path):
    3.     try:
    4.         df = pd.read_csv(csv_file_path)
    5.         df.to_excel(xls_file_path, index=False)
    6.         print(f"成功将 {csv_file_path} 转换为 {xls_file_path}")
    7.     except Exception as e:
    8.         print(f"转换过程中出现错误: {e}")

    9. # 示例调用
    10. csv_file = 'example.csv'
    11. xls_file = 'example.xls'
    12. csv_to_xls(csv_file, xls_file)
    复制代码
    7.3txt文件转cvs文件
    1. import pandas as pd

    2. def txt_to_csv(txt_file_path, csv_file_path):
    3.     try:
    4.         # 假设 txt 文件以空格分隔,根据实际情况修改 sep 参数
    5.         df = pd.read_csv(txt_file_path, sep=' ', header=None)
    6.         df.to_csv(csv_file_path, index=False, header=False)
    7.         print(f"成功将 {txt_file_path} 转换为 {csv_file_path}")
    8.     except Exception as e:
    9.         print(f"转换过程中出现错误: {e}")

    10. # 示例调用
    11. txt_file = 'example.txt'
    12. csv_file = 'example.csv'
    13. txt_to_csv(txt_file, csv_file)
    复制代码
    7.4csv文件转txt文件
    1. import pandas as pd

    2. def csv_to_txt(csv_file_path, txt_file_path):
    3.     try:
    4.         df = pd.read_csv(csv_file_path)
    5.         df.to_csv(txt_file_path, sep=' ', index=False, header=False)
    6.         print(f"成功将 {csv_file_path} 转换为 {txt_file_path}")
    7.     except Exception as e:
    8.         print(f"转换过程中出现错误: {e}")

    9. # 示例调用
    10. csv_file = 'example.csv'
    11. txt_file = 'example.txt'
    12. csv_to_txt(csv_file, txt_file)
    复制代码
    以上就是python中各种常见文件的读写操作与类型转换详细指南的详细内容,更多关于python文件读写与类型转换的资料请关注脚本之家其它相关文章!

    来源:https://www.jb51.net/python/339975dtt.htm
    免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

    本帖子中包含更多资源

    您需要 登录 才可以下载或查看,没有账号?立即注册

    ×

    最新评论

    QQ Archiver 手机版 小黑屋 福建二哥 ( 闽ICP备2022004717号|闽公网安备35052402000345号 )

    Powered by Discuz! X3.5 © 2001-2023

    快速回复 返回顶部 返回列表