5.2 python内置函数open()详解

帮助文档

help(open)

文档如下:

Help on built-in function open in module io:

open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
    Open file and return a stream.  Raise OSError upon failure.
    
    file is either a text or byte string giving the name (and the path
    if the file isn't in the current working directory) of the file to
    be opened or an integer file descriptor of the file to be
    wrapped. (If a file descriptor is given, it is closed when the
    returned I/O object is closed, unless closefd is set to False.)
    
    mode is an optional string that specifies the mode in which the file
    is opened. It defaults to 'r' which means open for reading in text
    mode.  Other common values are 'w' for writing (truncating the file if
    it already exists), 'x' for creating and writing to a new file, and
    'a' for appending (which on some Unix systems, means that all writes
    append to the end of the file regardless of the current seek position).
    In text mode, if encoding is not specified the encoding used is platform
    dependent: locale.getpreferredencoding(False) is called to get the
    current locale encoding. (For reading and writing raw bytes use binary
    mode and leave encoding unspecified.) The available modes are:
    
    ========= ===============================================================
    Character Meaning
    --------- ---------------------------------------------------------------
    'r'       open for reading (default)
    'w'       open for writing, truncating the file first
    'x'       create a new file and open it for writing
    'a'       open for writing, appending to the end of the file if it exists
    'b'       binary mode
    't'       text mode (default)
    '+'       open a disk file for updating (reading and writing)
    'U'       universal newline mode (deprecated)
    ========= ===============================================================
    
    The default mode is 'rt' (open for reading text). For binary random
    access, the mode 'w+b' opens and truncates the file to 0 bytes, while
    'r+b' opens the file without truncation. The 'x' mode implies 'w' and
    raises an `FileExistsError` if the file already exists.
    
    Python distinguishes between files opened in binary and text modes,
    even when the underlying operating system doesn't. Files opened in
    binary mode (appending 'b' to the mode argument) return contents as
    bytes objects without any decoding. In text mode (the default, or when
    't' is appended to the mode argument), the contents of the file are
    returned as strings, the bytes having been first decoded using a
    platform-dependent encoding or using the specified encoding if given.
    
    'U' mode is deprecated and will raise an exception in future versions
    of Python.  It has no effect in Python 3.  Use newline to control
    universal newlines mode.
    
    buffering is an optional integer used to set the buffering policy.
    Pass 0 to switch buffering off (only allowed in binary mode), 1 to select
    line buffering (only usable in text mode), and an integer > 1 to indicate
    the size of a fixed-size chunk buffer.  When no buffering argument is
    given, the default buffering policy works as follows:
    
    * Binary files are buffered in fixed-size chunks; the size of the buffer
      is chosen using a heuristic trying to determine the underlying device's
      "block size" and falling back on `io.DEFAULT_BUFFER_SIZE`.
      On many systems, the buffer will typically be 4096 or 8192 bytes long.
    
    * "Interactive" text files (files for which isatty() returns True)
      use line buffering.  Other text files use the policy described above
      for binary files.
    
    encoding is the name of the encoding used to decode or encode the
    file. This should only be used in text mode. The default encoding is
    platform dependent, but any encoding supported by Python can be
    passed.  See the codecs module for the list of supported encodings.
    
    errors is an optional string that specifies how encoding errors are to
    be handled---this argument should not be used in binary mode. Pass
    'strict' to raise a ValueError exception if there is an encoding error
    (the default of None has the same effect), or pass 'ignore' to ignore
    errors. (Note that ignoring encoding errors can lead to data loss.)
    See the documentation for codecs.register or run 'help(codecs.Codec)'
    for a list of the permitted encoding error strings.
    
    newline controls how universal newlines works (it only applies to text
    mode). It can be None, '', '\n', '\r', and '\r\n'.  It works as
    follows:
    
    * On input, if newline is None, universal newlines mode is
      enabled. Lines in the input can end in '\n', '\r', or '\r\n', and
      these are translated into '\n' before being returned to the
      caller. If it is '', universal newline mode is enabled, but line
      endings are returned to the caller untranslated. If it has any of
      the other legal values, input lines are only terminated by the given
      string, and the line ending is returned to the caller untranslated.
    
    * On output, if newline is None, any '\n' characters written are
      translated to the system default line separator, os.linesep. If
      newline is '' or '\n', no translation takes place. If newline is any
      of the other legal values, any '\n' characters written are translated
      to the given string.
    
    If closefd is False, the underlying file descriptor will be kept open
    when the file is closed. This does not work when a file name is given
    and must be True in that case.
    
    A custom opener can be used by passing a callable as *opener*. The
    underlying file descriptor for the file object is then obtained by
    calling *opener* with (*file*, *flags*). *opener* must return an open
    file descriptor (passing os.open as *opener* results in functionality
    similar to passing None).
    
    open() returns a file object whose type depends on the mode, and
    through which the standard file operations such as reading and writing
    are performed. When open() is used to open a file in a text mode ('w',
    'r', 'wt', 'rt', etc.), it returns a TextIOWrapper. When used to open
    a file in a binary mode, the returned class varies: in read binary
    mode, it returns a BufferedReader; in write binary and append binary
    modes, it returns a BufferedWriter, and in read/write mode, it returns
    a BufferedRandom.
    
    It is also possible to use a string or bytearray as a file for both
    reading and writing. For strings StringIO can be used like a file
    opened in a text mode, and for bytes a BytesIO can be used like a file
    opened in a binary mode.

普通操作

根据操作文档,我们可以知道一些操作信息:

1、基本操作

打开一个数据集压缩文件ant_bees_data.tar.gz:

在这里插入图片描述

open("D:/360MoveData/Users/lenovo/Desktop/test/ant_bees_data.tar.gz", "rb")

在这里插入图片描述

如图所示,打开文件成功,返回一个对象。

如文档所示,open() 的第一个参数是文件路径,第二个参数是模式,“rb”中的r表示只读方式打开,b表示以二进制方式打开。不同方式打开,会对文件施加不同作用,所以,需要根据实际情况选择模式,避免误操作,部分参数如下:

参数施加作用
w写的方式:文件存在则覆盖,不存在则创建
r读的方式:文件不存在即报错
a追加的方式:新写入的内容在最末尾,若文件不存在则创建
x创建的方式:文件存在则报错,不存在则创建

w+代表读写,r+代表读写,a+代表读写,三者有什么区别呢?

区别在于施加作用,如w+,它具有w的施加作用,而不具备r的施加作用。

如果不加参数,默认“rt”方式打开,即文本只读。

打开文件后,文件会以文件流的方式加载到内存中。流是个很有意思的词汇,中华文化的完美体现。(一直觉得流是写意的存在,贬义词除外):

流是用于处理网络连接的高级 async/await-ready 原语。流允许发送和接收数据,而不需要使用回调或低级协议和传输。

流,简单来说就是建立在面向对象基础上的一种抽象的处理数据的工具。在流中,定义了一些处理数据的基本操作,如读取数据,写入数据等,程序员是对流进行所有操作的,而不用关心流的另一头数据的真正流向。流不但可以处理文件,还可以处理动态内存、网络数据等多种数据形式。

2、对象

open()返回一个文件对象,其类型取决于模式。

在这里插入图片描述

如图,Buffered是不一样的,表明生成的缓存不一样,即“流派”不一样,操作也不一样。就好比武当派打的是太极,青城派使用的是暗器。

对象实例:
在这里插入图片描述

如图,在相同的打开方式,文件加载后,也是不同的实例。

3、如何优雅的open

通常我们打开文件后,是需要关闭的,关闭的方式是调用对象的close方法,如:

f = open("D:/360MoveData/Users/lenovo/Desktop/test/ant_bees_data002.tar.gz", "rb")
f.name
f.close()

在这里插入图片描述

等价于:

with open("D:/360MoveData/Users/lenovo/Desktop/test/ant_bees_data002.tar.gz", "rb") as f:
	f.name
	

上面的方式是python的上下文管理方法,通过该方式,自动调用了close()

在这里插入图片描述

大文件分块与合并

使用python的open,可以很容易实现分块与合并,而且代码不多。

(1)分块

在这里插入图片描述

import os
import math

# 文件路径
file_path = "D:/360MoveData/Users/lenovo/Desktop/test/ant_bees_data.tar.gz"
# 读取文件大小,单位为字节B
file_total_size = os.path.getsize(file_path)
print(file_total_size)
# 设置分块大小,每块为5M(1MB=1024KB,1KB=1024B)
chunk_size = 1024*1024*5
# 分块数量
chunks = math.ceil(file_total_size/chunk_size)
print(chunks)
# 切割文件,获取每一块文件,并保存
for chunk in range(chunks):
    print('chunk', chunk)
    if chunk+1 == chunks:
        is_end = 1
        current_size = file_total_size % chunk_size
    else:
        is_end = 0
        current_size = chunk_size

    offset=chunk*chunk_size  # 偏移量

    # 获取分块并保存
    with open(file_path, "rb") as targetFile:
    	# 获取偏移量
    	targetFile.seek(offset) # 从偏移量开始切割
    	# 保存分块为新文件
    	with open("D:/360MoveData/Users/lenovo/Desktop/test/ant_bees_data{}.tar.gz".format(chunk), "wb" ) as chunkfiles:
	    	chunkfiles.write(targetFile.read(current_size))  # 从偏移量开始,读current_size以获得该分块,并保存

运行代码后的效果:

在这里插入图片描述
(2)合并

将上面的分块,合并成一个新文件:

import os

filepath = "D:/360MoveData/Users/lenovo/Desktop/test/onefile.tar.gz"  # 合并后的新文件
chunk = 0
task ="ant_bees_data{}.tar.gz"  # 根据切块的规律设计占位
batchs_dir = "D:/360MoveData/Users/lenovo/Desktop/test/"  # 分块文件地址
with open(filepath, 'wb') as target_file:
	while True:
	    try:
	        filename=os.path.join(batchs_dir,task.format(chunk))
	        # 读取文件后进行保存
	        with open(filename, 'rb') as source_file:
	        	target_file.write(source_file.read())
	    except :
	        break
	    chunk += 1

运行代码后的效果:

在这里插入图片描述
解压看文件是否真的能用:

在这里插入图片描述
如上,真的可以用!

项目实战

需求:http接口,需要分块传输大文件,避免客户端奔溃。

通过上面,我们学会了如何分块,现在,我们运用于接口测试,通过requests进行分块请求,该流程为:调用login()方法登录系统,获得token;每切一块文件,就通过postChunks()方法上传该文件;上传文件后,调用addData()方法,请求后台接口合并文件,从而实现分块上传,后台合并的业务需求。

import os
import math
import json
import requests

class saveData(object):
    pass

def login():
    data={}
    # 登录用户
    url = "http://10.12.1.153:1027/logintp"
    data["user"] = "abc001"
    data["pwd"] = "abc001"
    res = requests.request("POST", url=url, data=data)
    setattr(saveData, "{}".format(data["user"]), json.loads(res.text)["data"]["token"])

def postChunks(chunks, chunk, file_path, offset, current_size):
    url = "http://10.12.1.153:1027/file/upload"
    payload = {"task_id": "task_id006","chunks": str(chunks),"chunk": str(chunk)}
    targetFile = open(file_path, "rb")
    targetFile.seek(offset)
    files = [("file", targetFile.read(current_size))]
    headers = {}
    headers["Authorization"] = "Bearer " + getattr(saveData, "abc001")
    response = requests.request("POST", url, headers=headers, data=payload, files=files)
    print(response.text)

def addData():
    url = "http://10.12.1.153:1027/file/merge"
    payload = {
        'task_id': 'task_id006',
        'filename': '10G_ant_bees_data.zip',
        'user': "abc001",
        'isoriginal': '1',
        'scene': '2',
        'batchname': 'test_id006'
    }
    headers = {}
    headers["Authorization"] = "Bearer " + getattr(saveData, "abc001")
    response = requests.request("POST", url, headers=headers, data=payload)
    print(response.text)


# 文件路径
file_path = "E:/training训练数据/10G_ant_bees_data.zip"
# 读取文件大小,单位为字节B
file_total_size = os.path.getsize(file_path)
print(file_total_size)
# 设置分块大小,每块为5M(1MB=1024KB,1KB=1024B)
chunk_size = 1024*1024*5
# 分块数量
chunks = math.ceil(file_total_size/chunk_size)
print(chunks)
# 登录,获取token
login()
# print(getattr(saveData, "abc001"))

# 每块发送一次请求
for chunk in range(chunks):
    print('chunk', chunk)
    if chunk+1 == chunks:
        is_end = 1
        current_size = file_total_size % chunk_size
    else:
        is_end = 0
        current_size = chunk_size
    # 发送一次请求
    postChunks(chunks=chunks, chunk=chunk, file_path=file_path, offset=chunk*chunk_size, current_size=current_size)

# 新增数据集
addData()

运行代码后的效果:

在这里插入图片描述
上面是内置函数open的实战应用,并通过requests实现了大文件的传输,避免系统奔溃。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Lion King

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值