• Python3操作文件系列(二):文件数据读写|二进制数据读写



    Python3操作文件系列(一):判断文件|目录是否存在三种方式

    Python3操作文件系列(二):文件数据读写|二进制数据读写

    Python3数据文件读取与写入

    Python3操作文件系列(三):excel文件读写数据





    一: 文件数据|二进制数据读写


    1. import os
    2. """
    3. Python3的open(file,mode="文件的操作模式")
    4. 利用该函数可以对文件和二进制文件进行只读,只写,读/写和追加等操作
    5. """
    6. pathFile = '../dataanalysis/file/fileData.txt'
    7. try:
    8. if os.path.exists(pathFile):
    9. with open(pathFile, "w") as file:
    10. file.write("你好,老杨,欢迎来到Python3操作文件的世界!")
    11. print("数据已成功写入 %s 文件!" % pathFile)
    12. else:
    13. print("文件: %s 不存在,下面将为你创建文件...........")
    14. # 创建文件,mode = w 才会创建不存在的文件
    15. with open(pathFile, 'w') as f:
    16. print("文件创建成功!")
    17. except IOError as err:
    18. print("系统错误: ", err)
    19. print("-----------------一次写入多行数据--------------------")
    20. try:
    21. with open(pathFile, 'w') as f:
    22. f.writelines(['Python3 这是第一行数据.....\n', 'Mongodb这是第二行数据....'])
    23. print("数据已写入")
    24. except IOError as err:
    25. print("系统异常: ", err)
    26. print()
    27. print("----------------------------读取文件的内容----------------------")
    28. try:
    29. with open(pathFile, 'r') as file:
    30. content = file.read()
    31. print("读到文件内容: %s" % content)
    32. print()
    33. print("输出内容后,文件指针已经只写末位,故下面无内容输出")
    34. print("读起10个字符: ", file.readline(5))
    35. except IOError as err:
    36. print("系统异常: ", err)
    37. try:
    38. with open(pathFile, 'r') as file:
    39. print()
    40. print("读起10个字符: ", file.readline(6))
    41. except IOError as err:
    42. print("系统异常: ", err)
    43. try:
    44. with open(pathFile, 'r') as file:
    45. print()
    46. print("读起多行内容(设置只读一行): ", file.readlines(1))
    47. print("读起多行内容(默认读取所有的行:): ", file.readlines())
    48. except IOError as err:
    49. print("系统异常: ", err)
    50. binaryPath = "../dataanalysis/file/binaryData.cad"
    51. try:
    52. with open(pathFile, 'a+') as f:
    53. f.writelines(['Python3 这是第一行数据.....\n',
    54. 'Mongodb这是第二行数据....',
    55. 'Python3 这是第一行数据.....\n',
    56. 'Python3 这是第一行数据.....\n',
    57. 'Python3 这是第一行数据.....\n'])
    58. print("数据已写入")
    59. except IOError as err:
    60. print("系统异常: ", err)
    61. try:
    62. with open(pathFile, 'r') as file:
    63. print()
    64. for line in file.readlines(-1):
    65. print("读取文件所有行: ", line)
    66. except IOError as err:
    67. print("系统异常: ", err)
    68. print('-------------------读写二进制文件数据----------------------')
    69. try:
    70. with open(binaryPath, 'wb') as file:
    71. # 用字符串表示坐标数据,转换为字节流,吸入文件
    72. # 注意数据之间用空格进行分隔
    73. file.write(bytes(('100000 ' + '10 ' + '20 ' + '29 ' + '22 ' + '30'), 'utf-8'))
    74. except IOError as err:
    75. print("系统异常: ", err)
    76. print("读取二进制文件")
    77. try:
    78. with open(binaryPath, 'rb') as file:
    79. line = file.read().decode("utf-8")
    80. lines = line.split(" ")
    81. for item in lines:
    82. print("存入文件的二进制项为: ", item)
    83. except IOError as err:
    84. print("系统异常: ", err)


    二: 文件数据|二进制数据读写运行效果


    D:\program_file_worker\anaconda\python.exe D:\program_file_worker\python_source_work\SSO\grammar\file\FileReadOperationByOpen.py 
    数据已成功写入 ../dataanalysis/file/fileData.txt 文件!
    -----------------一次写入多行数据--------------------
    数据已写入

    ----------------------------读取文件的内容----------------------
    读到文件内容: Python3 这是第一行数据.....
    Mongodb这是第二行数据....

    输出内容后,文件指针已经只写末位,故下面无内容输出
    读起10个字符:  

    读起10个字符:  Python

    读起多行内容(设置只读一行):  ['Python3 这是第一行数据.....\n']
    读起多行内容(默认读取所有的行:):  ['Mongodb这是第二行数据....']
    数据已写入

    读取文件所有行:  Python3 这是第一行数据.....

    读取文件所有行:  Mongodb这是第二行数据....Python3 这是第一行数据.....

    读取文件所有行:  Mongodb这是第二行数据....Python3 这是第一行数据.....

    读取文件所有行:  Python3 这是第一行数据.....

    读取文件所有行:  Python3 这是第一行数据.....

    -------------------读写二进制文件数据----------------------
    读取二进制文件
    存入文件的二进制项为:  100000
    存入文件的二进制项为:  10
    存入文件的二进制项为:  20
    存入文件的二进制项为:  29
    存入文件的二进制项为:  22
    存入文件的二进制项为:  30

    Process finished with exit code 0
     

    三: struct模块读写二进制数据


    Python3通过struct模块处理二进制数据文件,利用该函数可以对文件和二进制文件进行只读,只写,读/写和追加等操作该模块使用:
    pack()函数对二进制数据进行编码操作
    unpack()函数对二进制数据进行解码操作

    1. import os
    2. from struct import *
    3. """
    4. Python3通过struct模块处理二进制数据文件
    5. 利用该函数可以对文件和二进制文件进行只读,只写,读/写和追加等操作
    6. 该模块使用pack()函数对二进制数据进行编码操作
    7. unpack()函数对二进制数据进行解码操作
    8. """
    9. print("""
    10. Python的struct模块对二进制文件的数据读写进行了简化
    11. 我们在写数据时,使用struct模块的pack()函数将坐标系数据转化为字符串,然后写入字符串
    12. 函数的语法格式如下:
    13. pack(fmt,v1,v2) 其中fmt参数指定数据类型,如整数数字用i来表示,浮点数字用'f'来表示,按照先后顺序,每个数字都需要指定数据类型
    14. """)
    15. pathFile = '../dataanalysis/file/fileData.db'
    16. try:
    17. with open(pathFile, 'wb') as file:
    18. print("写入数据,4个坐标值都是整数数字|转换为字符串进行存储,并对二进制数据进行编码操作")
    19. file.write(pack('iiii', 10, 10, 100, 200))
    20. print("二进制数据写入成功")
    21. except IOError as err:
    22. print("系统异常: ", err)
    23. print()
    24. print("使用struct模块中的unpack()函数读取二进制数据")
    25. try:
    26. with open(pathFile, 'rb') as inputStream:
    27. print('使用unpack()函数进行解码操作')
    28. result = (a, b, c, d) = unpack('iiii', inputStream.read())
    29. print(a, b, c, d)
    30. print("a的数据类型: ", type(a))
    31. for item in list(result):
    32. print("二进坐标解码后的数字: %d" % item)
    33. except IOError as err:
    34. print("系统异常: ", err)

     
     

    四: struct模块读写二进制数据运行效果


    D:\program_file_worker\anaconda\python.exe D:\program_file_worker\python_source_work\SSO\grammar\file\FileReadWriterBinaryStruct.py 

        Python的struct模块对二进制文件的数据读写进行了简化
        我们在写数据时,使用struct模块的pack()函数将坐标系数据转化为字符串,然后写入字符串
        函数的语法格式如下:
          pack(fmt,v1,v2) 其中fmt参数指定数据类型,如整数数字用i来表示,浮点数字用'f'来表示,按照先后顺序,每个数字都需要指定数据类型

    写入数据,4个坐标值都是整数数字|转换为字符串进行存储,并对二进制数据进行编码操作
    二进制数据写入成功

    使用struct模块中的unpack()函数读取二进制数据
    使用unpack()函数进行解码操作
    10 10 100 200
    a的数据类型:  
    二进坐标解码后的数字: 10
    二进坐标解码后的数字: 10
    二进坐标解码后的数字: 100
    二进坐标解码后的数字: 200

    Process finished with exit code 0
     

    五: os模块对文件的常规操作


    1. import os
    2. """
    3. Python3使用os模块对文件,目录,路径的常规操作
    4. os模块对文件进行读写外,还封装看操作目录,路径,系统的相关方法
    5. """
    6. print("""
    7. -----------------对文件的操作-------------------------
    8. 主要就是读写文件数据,创建,删除文件,修改权限等操作,通常使用open(file,[mode])函数来完成
    9. """)
    10. print(
    11. "下面使用os模块的write函数向文件中写入数据,数据使用字符串表示,并使用encode函数以指定的编码方式进行编码,最后不关闭文件")
    12. pathFile = '../dataanalysis/file/readWriteData.txt'
    13. newPathFile = '../dataanalysis/file/readWriteDataNew.txt'
    14. try:
    15. file = os.open(pathFile, os.O_RDWR | os.O_CREAT | os.O_TEXT)
    16. print("用utf-8编码的方式写入字符串")
    17. os.write(file, "你好,欢迎来到Python编程世界".encode("utf-8"))
    18. print("关闭文件")
    19. os.close(file)
    20. except IOError as err:
    21. print("系统异常: ", err)
    22. try:
    23. print("以只读的方式打开文件")
    24. file = os.open(pathFile, os.O_RDONLY)
    25. print("用utf-8编码的方式解码")
    26. result = os.read(file, 18).decode('utf-8', 'ignore')
    27. print("result: %s" % result)
    28. print("关闭文件")
    29. os.close(file)
    30. except IOError as err:
    31. print("系统异常: ", err)
    32. try:
    33. print()
    34. print('使用rename函数修改文件')
    35. if os.path.exists(newPathFile): # readWriterDataNew.txt 文件存在,则移除,否则下面的重命名时会报错,说文件已经存在
    36. os.remove(newPathFile)
    37. print("重命名后,源文件将不存在")
    38. os.rename(pathFile, newPathFile)
    39. print("移除文件readWriterData.txt")
    40. print('-----------------------------判断readWriterDataNew.txt的权限--------')
    41. print("判断移除文件readWriterDataNew.txt的权限")
    42. result_w = os.access(newPathFile, os.W_OK)
    43. print("readWriterDataNew.txt文件有写的权限吗:", result_w)
    44. result_r = os.access(newPathFile, os.R_OK)
    45. print("readWriterDataNew.txt文件有读的权限吗:", result_r)
    46. result_x = os.access(newPathFile, os.X_OK)
    47. print("readWriterDataNew.txt文件有执行的权限吗:", result_x)
    48. except IOError as err:
    49. print("系统异常: ", err)

     
     

    六: os模块对文件的常规操作运行效果



    D:\program_file_worker\anaconda\python.exe D:\program_file_worker\python_source_work\SSO\grammar\file\FileReadWriterPathAndDicOrFile.py 

       -----------------对文件的操作-------------------------
       主要就是读写文件数据,创建,删除文件,修改权限等操作,通常使用open(file,[mode])函数来完成

    下面使用os模块的write函数向文件中写入数据,数据使用字符串表示,并使用encode函数以指定的编码方式进行编码,最后不关闭文件
    用utf-8编码的方式写入字符串
    关闭文件
    以只读的方式打开文件
    用utf-8编码的方式解码
    result: 你好,欢迎来
    关闭文件

    使用rename函数修改文件
    重命名后,源文件将不存在
    移除文件readWriterData.txt
    -----------------------------判断readWriterDataNew.txt的权限--------
    判断移除文件readWriterDataNew.txt的权限
    readWriterDataNew.txt文件有写的权限吗: True
    readWriterDataNew.txt文件有读的权限吗: True
    readWriterDataNew.txt文件有执行的权限吗: True

    Process finished with exit code 0
     

    七: os模块对目录及路径操作 


    1. import os
    2. import stat
    3. import platform
    4. import sys
    5. import time
    6. """
    7. Python3使用os模块对文件,目录,路径的常规操作
    8. os模块对文件进行读写外,还封装看操作目录,路径,系统的相关方法
    9. """
    10. print("""
    11. Python中的os模块对路径|目录的常规操作
    12. """)
    13. pathDir = '../dataanalysis/file/data/'
    14. try:
    15. print("os模块对目录的相关操作")
    16. print("判断该目录是否存在: ", os.path.exists(pathDir))
    17. if os.path.exists(pathDir):
    18. result_w = os.access(pathDir, os.W_OK)
    19. print("data文件有写的权限吗:", result_w)
    20. result_r = os.access(pathDir, os.R_OK)
    21. print("pathDir文件有读的权限吗:", result_r)
    22. result_x = os.access(pathDir, os.X_OK)
    23. print("pathDir文件有执行的权限吗:", result_x)
    24. print("目录存在先删除,否则已经存在,不能创建,会报错...")
    25. os.chmod(pathDir, stat.S_IWRITE) # 将只读设置为可写
    26. #
    27. # 移除目录dir; os.remove()会报错 [WinError 5] 拒绝访问。: '../dataanalysis/file/data/'
    28. os.rmdir(pathDir)
    29. print("创建一个新的目录(pathFile)")
    30. os.mkdir(pathDir)
    31. print("判断是否是目录:", os.path.isdir(pathDir))
    32. print("获取当前工作目录: ", os.getcwd())
    33. print()
    34. print('创建多层目录')
    35. if os.path.exists(os.getcwd() + '/system/jd/data/'):
    36. # 删除空文件夹,如个文件夹中有文件,则不能删除
    37. os.rmdir(os.getcwd() + '/system/jd/data/')
    38. os.makedirs(os.getcwd() + '/system/jd/data/')
    39. print('改变当前目录:')
    40. os.chdir(os.getcwd())
    41. print("再次获取当前工作目录: ", os.getcwd())
    42. print()
    43. print("判断是否是目录:", os.path.isdir(os.getcwd() + '/system/jd/data/'))
    44. print("判断是否是文件:", os.path.isfile(os.getcwd() + '/system/jd/data/'))
    45. print('改变当前目录:')
    46. os.chdir(os.getcwd())
    47. if os.path.exists(os.getcwd() + '/system00/jd00/data002/'):
    48. # 先移除文件
    49. os.remove(os.getcwd() + '/system00/jd00/data002/data.txt')
    50. # 删除空文件夹,如个文件夹中有文件,则不能删除
    51. os.rmdir(os.getcwd() + '/system00/jd00/data002/')
    52. os.makedirs(os.getcwd() + '/system00/jd00/data002/')
    53. print('返回文件名: ', os.path.basename(os.getcwd() + '/system00/jd00/data002/data.txt'))
    54. with open(os.getcwd() + '/system00/jd00/data002/data.txt', 'w') as file:
    55. file.writelines("你好呀,欢迎来到梦的世界!\n 你将再这里实现财务自由")
    56. print("获取文件的大小: ", os.path.getsize(os.getcwd() + '/system00/jd00/data002/data.txt'))
    57. print()
    58. print("当前系统运行环境(nt表示window系统):", os.name)
    59. print("系统的文件分割符: ", os.sep)
    60. print("系统终止符: ", os.linesep)
    61. s = platform.platform()
    62. print("当前系统: ", s) # 获取当前系统信息
    63. p = sys.path
    64. print("当前安装路径: ", p) # 当前安装路径
    65. op = os.getcwd()
    66. print("当前代码路径: ", op) # 获取当前代码路径
    67. print("Python版本信息: ", sys.version_info)
    68. print("========================================================")
    69. print(time.time())
    70. print(time.localtime(time.time()).tm_year)
    71. print(time.process_time_ns())
    72. except IOError as err:
    73. print("系统异常: ", err)

     
    

    八: os模块对目录及路径操作运行效果


    D:\program_file_worker\anaconda\python.exe D:\program_file_worker\python_source_work\SSO\grammar\file\FileReadWriterPathDirOperation.py 

        Python中的os模块对路径|目录的常规操作

    os模块对目录的相关操作
    判断该目录是否存在:  True
    data文件有写的权限吗: True
    pathDir文件有读的权限吗: True
    pathDir文件有执行的权限吗: True
    目录存在先删除,否则已经存在,不能创建,会报错...
    创建一个新的目录(pathFile)
    判断是否是目录: True
    获取当前工作目录:  D:\program_file_worker\python_source_work\SSO\grammar\file

    创建多层目录
    改变当前目录:
    再次获取当前工作目录:  D:\program_file_worker\python_source_work\SSO\grammar\file

    判断是否是目录: True
    判断是否是文件: False
    改变当前目录:
    返回文件名:  data.txt
    获取文件的大小:  71

    当前系统运行环境(nt表示window系统): nt
    系统的文件分割符:  \
    系统终止符:  

    当前系统:  Windows-10-10.0.22621-SP0
    当前安装路径:  ['D:\\program_file_worker\\python_source_work\\SSO\\grammar\\file', 'D:\\program_file_worker\\python_source_work', 'D:\\program_file_worker\\anaconda\\python311.zip', 'D:\\program_file_worker\\anaconda\\DLLs', 'D:\\program_file_worker\\anaconda\\Lib', 'D:\\program_file_worker\\anaconda', 'D:\\program_file_worker\\anaconda\\Lib\\site-packages', 'D:\\program_file_worker\\anaconda\\Lib\\site-packages\\win32', 'D:\\program_file_worker\\anaconda\\Lib\\site-packages\\win32\\lib', 'D:\\program_file_worker\\anaconda\\Lib\\site-packages\\Pythonwin']
    当前代码路径:  D:\program_file_worker\python_source_work\SSO\grammar\file
    Python版本信息:  sys.version_info(major=3, minor=11, micro=4, releaselevel='final', serial=0)
    ========================================================
    1696776642.830574
    2023
    156250000

    Process finished with exit code 0
     

  • 相关阅读:
    若依的放接口表单数据重复提交疑问
    数据分析必备:6大步骤+5大类型+2大分析方法
    控制算法::速度前馈
    面试算法25:链表中的数字相加
    5.16 加载内核映像文件(2)
    html div && span 容器元素
    .NET Core 日志系统
    Hive 表注释乱码解决
    2023年五一杯数学建模A题无人机定点投放问题求解全过程论文及程序
    C语言文件操作
  • 原文地址:https://blog.csdn.net/u014635374/article/details/133658521