【Python零基础入门笔记 | 14】深度学习如何保存训练好的模型,请看数据持久化之文件操作(1)

这是机器未来的第25篇文章

原文首发地址:https://blog.csdn.net/RobotFutures/article/details/125647298

1. 概述

数据在计算机中有2种存储方式,一种是在内存中,一种是在硬盘中,内存存储运行过程中的数据,如果数据需要掉电或程序退出后仍然能够保存,那么就需要存储到文件中,进行持久化存储。

2. 文件操作流

文件的典型流程为:打开文件->读写文件->关闭文件

# 写文件
f = open(file="demo.txt", mode="w")
f.write("机器未来,追逐未来时代的脉搏")
f.close()

进行写操作后,可以看到目录下多了一个demo.txt文件,打开后可以看到其内容为:机器未来,追逐未来时代的脉搏

# 读文件
f = open(file="demo.txt", mode="r")
print(f.read())
f.close()
机器未来,追逐未来时代的脉搏

3. open函数详解

先来看一下open函数的函数描述

open??
Output exceeds the size limit. Open the full output data in a text editor
Signature:
open(
    file,
    mode='r',
    buffering=-1,
    encoding=None,
    errors=None,
    newline=None,
    closefd=True,
    opener=None,
)
Docstring:

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.
[0;31mType:[0m      builtin_function_or_method

可以看到open函数的功能为打开一个文件,返回一个文件流句柄。open的参数较多,平常用的最多的就是3个file、mode、encoding。

3.1 file参数

先来看一下file参数,file参数为将要打开的文件名称,支持相对路径和绝对路径。

3.1.1 相对路径

相对路径是以程序当前运行目录为基准路径向上或向下的路径地址。

在聊相对路径之前,先来看看两个特殊的目录:【.】目录和【…】目录。
在命令行界面下,输入dir -a或ls -la即可看到这两个特殊目录。

zsm@zsm:python14$ ls -la
total 16
drwxrwxrwx 1 zhoushimin zhoushimin     0 Jul  3 21:03 .
drwxrwxrwx 1 zhoushimin zhoushimin 16384 Jul  3 21:00 ..
drwxrwxrwx 1 zhoushimin zhoushimin     0 Jul  3 21:01 a
drwxrwxrwx 1 zhoushimin zhoushimin     0 Jul  3 21:02 b

【.】目录代表当前目录,【…】目录代表父目录或上一级目录,在相对路径的使用中非常好用。

以下面的目录结构为例

.
├── a
│   ├── a1
│   │   ├── app.py
│   │   └── test.txt
│   └── a2
└── b
    ├── b1
    │   └── b1.txt
    └── b2

python程序为app.py, 程序的运行目录即为./a/a1/

同级目录文件访问:

它和test.txt在同一个目录,如果要打开test.txt,直接填写test.txt即可,或者加上当前目录【./】也可以,即./test.txt

直接填写文件名

# 在文件a/a1/app.py中写入下列代码
# 读文件
f = open(file="test.txt", mode="r")
print(f.read())
f.close()

执行结果如下:

zsm@zsm:a1$ ls
app.py  test.txt
zsm@zsm:a1$ python app.py 
机器未来,追逐未来时代的脉搏

以【.】目录相对定位

# 在文件a/a1/app.py中写入下列代码
# 读文件
f = open(file="./test.txt", mode="r")
print(f.read())
f.close()

执行结果如下,一模一样:

zsm@zsm:a1$ ls
app.py  test.txt
zsm@zsm:a1$ python app.py 
机器未来,追逐未来时代的脉搏

跨目录访问文件:

如果要访问b1.txt,该如何填写相对路径呢?我们善用【…】访问上级目录。

我们用…/…/b/b1/b1.txt这个相对路径地址访问b1.txt,第一个…/代表回到上级目录a,第二个…/代表回到根目录,然后从根目录访问b/b1/b1.txt。我们在b1中写入【这里是b1】

看代码!

# 读文件
f = open(file="../../b/b1/b1.txt", mode="r")
print(f.read())
f.close()

输出结果:

zsm@zsm:a1$ ls
app.py  test.txt
zsm@zsm:a1$ python app.py 
这里是b1

3.1.2 绝对路径

绝对路径是以系统根目录(linux)或硬盘分区根目录盘符开始的绝对定位路径。

例如test.txt文件的绝对路径如下:

/home/zsm/python14/a/a1/test.txt

我们将绝对路径填充open的file参数,可以获得同样的运行结果。

# 读文件
f = open(file="/home/zsm/python14/a/a1/test.txt", mode="r")
print(f.read())
f.close()

特别注意:绝对路径地址一定要以根目录/开始(linux)或者盘符开始(windows)

3.2 mode参数

模式 描述
t 文本模式 (默认)。
x 写模式,新建一个文件,如果该文件已存在则会报错。
b 二进制模式。
+ 打开一个文件进行更新(可读可写)。
U 通用换行模式(不推荐)。
r 以只读方式打开文件。文件的指针将会放在文件的开头。这是默认模式。
rb 以二进制格式打开一个文件用于只读。文件指针将会放在文件的开头。这是默认模式。一般用于非文本文件如图片等。
r+ 打开一个文件用于读写。文件指针将会放在文件的开头。
rb+ 以二进制格式打开一个文件用于读写。文件指针将会放在文件的开头。一般用于非文本文件如图片等。
w 打开一个文件只用于写入。如果该文件已存在则打开文件,并从开头开始编辑,即原有内容会被删除。如果该文件不存在,创建新文件。
wb 以二进制格式打开一个文件只用于写入。如果该文件已存在则打开文件,并从开头开始编辑,即原有内容会被删除。如果该文件不存在,创建新文件。一般用于非文本文件如图片等。
w+ 打开一个文件用于读写。如果该文件已存在则打开文件,并从开头开始编辑,即原有内容会被删除。如果该文件不存在,创建新文件。
wb+ 以二进制格式打开一个文件用于读写。如果该文件已存在则打开文件,并从开头开始编辑,即原有内容会被删除。如果该文件不存在,创建新文件。一般用于非文本文件如图片等。
a 打开一个文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾。也就是说,新的内容将会被写入到已有内容之后。如果该文件不存在,创建新文件进行写入。
ab 以二进制格式打开一个文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾。也就是说,新的内容将会被写入到已有内容之后。如果该文件不存在,创建新文件进行写入。
a+ 打开一个文件用于读写。如果该文件已存在,文件指针将会放在文件的结尾。文件打开时会是追加模式。如果该文件不存在,创建新文件用于读写。
ab+ 以二进制格式打开一个文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾。如果该文件不存在,创建新文件用于读写。

mode的参数组合非常多,那么如何快速理解mode的参数呢?

请看下一节http://t.csdn.cn/9NvUp

《Python零基础快速入门系列》快速导航:

写在末尾:

  • 博客简介:专注AIoT领域,追逐未来时代的脉搏,记录路途中的技术成长!
  • 专栏简介:本专栏的核心就是:快!快!快!2周快速拿下Python,具备项目开发能力,为机器学习和深度学习做准备。
  • 面向人群:零基础编程爱好者
  • 专栏计划:接下来会逐步发布跨入人工智能的系列博文,敬请期待
    • Python零基础快速入门系列
    • 快速入门Python数据科学系列
    • 人工智能开发环境搭建系列
    • 机器学习系列
    • 物体检测快速入门系列
    • 自动驾驶物体检测系列

猜你喜欢

转载自blog.csdn.net/RobotFutures/article/details/125647298