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

本文围绕Python3操作文件展开,介绍了文件数据与二进制数据读写、struct模块读写二进制数据、os模块对文件的常规操作及对目录和路径的操作,并展示了各操作的运行效果,涉及文件的读写、创建、删除、重命名,以及目录的创建、权限判断等内容。


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

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

Python3数据文件读取与写入

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





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


import os

"""
  Python3的open(file,mode="文件的操作模式")
  利用该函数可以对文件和二进制文件进行只读,只写,读/写和追加等操作
"""
pathFile = '../dataanalysis/file/fileData.txt'
try:
    if os.path.exists(pathFile):
        with open(pathFile, "w") as file:
            file.write("你好,老杨,欢迎来到Python3操作文件的世界!")
            print("数据已成功写入 %s 文件!" % pathFile)
    else:
        print("文件: %s 不存在,下面将为你创建文件...........")
        # 创建文件,mode = w 才会创建不存在的文件
        with open(pathFile, 'w') as f:
            print("文件创建成功!")
except IOError as err:
    print("系统错误: ", err)

print("-----------------一次写入多行数据--------------------")

try:
    with open(pathFile, 'w') as f:
        f.writelines(['Python3 这是第一行数据.....\n', 'Mongodb这是第二行数据....'])
        print("数据已写入")
except IOError as err:
    print("系统异常: ", err)
print()
print("----------------------------读取文件的内容----------------------")

try:
    with open(pathFile, 'r') as file:
        content = file.read()
        print("读到文件内容: %s" % content)
        print()
        print("输出内容后,文件指针已经只写末位,故下面无内容输出")
        print("读起10个字符: ", file.readline(5))
except IOError as err:
    print("系统异常: ", err)

try:
    with open(pathFile, 'r') as file:
        print()
        print("读起10个字符: ", file.readline(6))
except IOError as err:
    print("系统异常: ", err)

try:
    with open(pathFile, 'r') as file:
        print()
        print("读起多行内容(设置只读一行): ", file.readlines(1))
        print("读起多行内容(默认读取所有的行:): ", file.readlines())
except IOError as err:
    print("系统异常: ", err)
binaryPath = "../dataanalysis/file/binaryData.cad"

try:
    with open(pathFile, 'a+') as f:
        f.writelines(['Python3 这是第一行数据.....\n',
                      'Mongodb这是第二行数据....',
                      'Python3 这是第一行数据.....\n',
                      'Python3 这是第一行数据.....\n',
                      'Python3 这是第一行数据.....\n'])
        print("数据已写入")
except IOError as err:
    print("系统异常: ", err)
try:
    with open(pathFile, 'r') as file:
        print()
        for line in file.readlines(-1):
            print("读取文件所有行: ", line)
except IOError as err:
    print("系统异常: ", err)

print('-------------------读写二进制文件数据----------------------')
try:
    with open(binaryPath, 'wb') as file:
        # 用字符串表示坐标数据,转换为字节流,吸入文件
        # 注意数据之间用空格进行分隔
        file.write(bytes(('100000 ' + '10 ' + '20 ' + '29 ' + '22 ' + '30'), 'utf-8'))
except IOError as err:
    print("系统异常: ", err)
print("读取二进制文件")
try:
    with open(binaryPath, 'rb') as file:
        line = file.read().decode("utf-8")
        lines = line.split(" ")
        for item in lines:
            print("存入文件的二进制项为: ", item)

except IOError as err:
    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()函数对二进制数据进行解码操作

import os
from struct import *

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

print("""
    Python的struct模块对二进制文件的数据读写进行了简化
    我们在写数据时,使用struct模块的pack()函数将坐标系数据转化为字符串,然后写入字符串
    函数的语法格式如下:
      pack(fmt,v1,v2) 其中fmt参数指定数据类型,如整数数字用i来表示,浮点数字用'f'来表示,按照先后顺序,每个数字都需要指定数据类型
""")
pathFile = '../dataanalysis/file/fileData.db'
try:
    with open(pathFile, 'wb') as file:
        print("写入数据,4个坐标值都是整数数字|转换为字符串进行存储,并对二进制数据进行编码操作")
        file.write(pack('iiii', 10, 10, 100, 200))
        print("二进制数据写入成功")
except IOError as err:
    print("系统异常: ", err)
print()
print("使用struct模块中的unpack()函数读取二进制数据")

try:
    with open(pathFile, 'rb') as inputStream:
        print('使用unpack()函数进行解码操作')
        result = (a, b, c, d) = unpack('iiii', inputStream.read())
        print(a, b, c, d)
        print("a的数据类型: ", type(a))
        for item in list(result):
            print("二进坐标解码后的数字: %d" % item)

except IOError as err:
    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的数据类型:  <class 'int'>
二进坐标解码后的数字: 10
二进坐标解码后的数字: 10
二进坐标解码后的数字: 100
二进坐标解码后的数字: 200

Process finished with exit code 0
 

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


import os

"""
  Python3使用os模块对文件,目录,路径的常规操作
     os模块对文件进行读写外,还封装看操作目录,路径,系统的相关方法
"""

print("""
   -----------------对文件的操作-------------------------
   主要就是读写文件数据,创建,删除文件,修改权限等操作,通常使用open(file,[mode])函数来完成
""")
print(
    "下面使用os模块的write函数向文件中写入数据,数据使用字符串表示,并使用encode函数以指定的编码方式进行编码,最后不关闭文件")

pathFile = '../dataanalysis/file/readWriteData.txt'
newPathFile = '../dataanalysis/file/readWriteDataNew.txt'
try:
    file = os.open(pathFile, os.O_RDWR | os.O_CREAT | os.O_TEXT)
    print("用utf-8编码的方式写入字符串")
    os.write(file, "你好,欢迎来到Python编程世界".encode("utf-8"))
    print("关闭文件")
    os.close(file)
except IOError as err:
    print("系统异常: ", err)

try:
    print("以只读的方式打开文件")
    file = os.open(pathFile, os.O_RDONLY)
    print("用utf-8编码的方式解码")
    result = os.read(file, 18).decode('utf-8', 'ignore')
    print("result: %s" % result)
    print("关闭文件")
    os.close(file)
except IOError as err:
    print("系统异常: ", err)

try:
    print()
    print('使用rename函数修改文件')
    if os.path.exists(newPathFile):  # readWriterDataNew.txt 文件存在,则移除,否则下面的重命名时会报错,说文件已经存在
        os.remove(newPathFile)
    print("重命名后,源文件将不存在")
    os.rename(pathFile, newPathFile)
    print("移除文件readWriterData.txt")
    print('-----------------------------判断readWriterDataNew.txt的权限--------')
    print("判断移除文件readWriterDataNew.txt的权限")
    result_w = os.access(newPathFile, os.W_OK)
    print("readWriterDataNew.txt文件有写的权限吗:", result_w)
    result_r = os.access(newPathFile, os.R_OK)
    print("readWriterDataNew.txt文件有读的权限吗:", result_r)
    result_x = os.access(newPathFile, os.X_OK)
    print("readWriterDataNew.txt文件有执行的权限吗:", result_x)
except IOError as err:
    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模块对目录及路径操作 


import os
import stat
import platform
import sys
import time

"""
  Python3使用os模块对文件,目录,路径的常规操作
     os模块对文件进行读写外,还封装看操作目录,路径,系统的相关方法
"""

print("""
    Python中的os模块对路径|目录的常规操作
""")
pathDir = '../dataanalysis/file/data/'

try:
    print("os模块对目录的相关操作")
    print("判断该目录是否存在: ", os.path.exists(pathDir))
    if os.path.exists(pathDir):
        result_w = os.access(pathDir, os.W_OK)
        print("data文件有写的权限吗:", result_w)
        result_r = os.access(pathDir, os.R_OK)
        print("pathDir文件有读的权限吗:", result_r)
        result_x = os.access(pathDir, os.X_OK)
        print("pathDir文件有执行的权限吗:", result_x)
        print("目录存在先删除,否则已经存在,不能创建,会报错...")
        os.chmod(pathDir, stat.S_IWRITE)  # 将只读设置为可写
        #
        # 移除目录dir; os.remove()会报错 [WinError 5] 拒绝访问。: '../dataanalysis/file/data/'
        os.rmdir(pathDir)
    print("创建一个新的目录(pathFile)")
    os.mkdir(pathDir)
    print("判断是否是目录:", os.path.isdir(pathDir))
    print("获取当前工作目录: ", os.getcwd())
    print()
    print('创建多层目录')
    if os.path.exists(os.getcwd() + '/system/jd/data/'):
        # 删除空文件夹,如个文件夹中有文件,则不能删除
        os.rmdir(os.getcwd() + '/system/jd/data/')
    os.makedirs(os.getcwd() + '/system/jd/data/')
    print('改变当前目录:')
    os.chdir(os.getcwd())
    print("再次获取当前工作目录: ", os.getcwd())
    print()
    print("判断是否是目录:", os.path.isdir(os.getcwd() + '/system/jd/data/'))
    print("判断是否是文件:", os.path.isfile(os.getcwd() + '/system/jd/data/'))
    print('改变当前目录:')
    os.chdir(os.getcwd())
    if os.path.exists(os.getcwd() + '/system00/jd00/data002/'):
        # 先移除文件
        os.remove(os.getcwd() + '/system00/jd00/data002/data.txt')
        # 删除空文件夹,如个文件夹中有文件,则不能删除
        os.rmdir(os.getcwd() + '/system00/jd00/data002/')
    os.makedirs(os.getcwd() + '/system00/jd00/data002/')
    print('返回文件名: ', os.path.basename(os.getcwd() + '/system00/jd00/data002/data.txt'))
    with open(os.getcwd() + '/system00/jd00/data002/data.txt', 'w') as file:
        file.writelines("你好呀,欢迎来到梦的世界!\n 你将再这里实现财务自由")

    print("获取文件的大小: ", os.path.getsize(os.getcwd() + '/system00/jd00/data002/data.txt'))
    print()
    print("当前系统运行环境(nt表示window系统):", os.name)
    print("系统的文件分割符: ", os.sep)
    print("系统终止符: ", os.linesep)

    s = platform.platform()
    print("当前系统: ", s)  # 获取当前系统信息
    p = sys.path
    print("当前安装路径: ", p)  # 当前安装路径
    op = os.getcwd()
    print("当前代码路径: ", op)  # 获取当前代码路径
    print("Python版本信息: ", sys.version_info)
    print("========================================================")
    print(time.time())
    print(time.localtime(time.time()).tm_year)
    print(time.process_time_ns())
except IOError as err:
    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
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值