0


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

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

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

1. 概述

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

2. 文件操作流

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

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

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

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

3. open函数详解

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

  1. open??
  1. Output exceeds the size limit. Open the full output data in a text editor
  2. Signature:
  3. open(
  4. file,
  5. mode='r',
  6. buffering=-1,
  7. encoding=None,
  8. errors=None,
  9. newline=None,
  10. closefd=True,
  11. opener=None,
  12. )
  13. Docstring:
  14. Open file and return a stream. Raise OSError upon failure.
  15. file is either a text or byte string giving the name (and the path
  16. if the file isn't in the current working directory) of the file to
  17. be opened or an integer file descriptor of the file to be
  18. wrapped. (If a file descriptor is given, it is closed when the
  19. returned I/O object is closed, unless closefd is set to False.)
  20. mode is an optional string that specifies the mode in which the file
  21. is opened. It defaults to 'r' which means open for reading in text
  22. mode. Other common values are 'w' for writing (truncating the file if
  23. it already exists), 'x' for creating and writing to a new file, and
  24. 'a' for appending (which on some Unix systems, means that all writes
  25. append to the end of the file regardless of the current seek position).
  26. In text mode, if encoding is not specified the encoding used is platform
  27. dependent: locale.getpreferredencoding(False) is called to get the
  28. current locale encoding. (For reading and writing raw bytes use binary
  29. mode and leave encoding unspecified.) The available modes are:
  30. ========= ===============================================================
  31. Character Meaning
  32. --------- ---------------------------------------------------------------
  33. 'r' open for reading (default)
  34. 'w' open for writing, truncating the file first
  35. 'x' create a new file and open it for writing
  36. 'a' open for writing, appending to the end of the file if it exists
  37. 'b' binary mode
  38. 't' text mode (default)
  39. '+' open a disk file for updating (reading and writing)
  40. 'U' universal newline mode (deprecated)
  41. ========= ===============================================================
  42. The default mode is 'rt' (open for reading text). For binary random
  43. access, the mode 'w+b' opens and truncates the file to 0 bytes, while
  44. 'r+b' opens the file without truncation. The 'x' mode implies 'w' and
  45. raises an `FileExistsError` if the file already exists.
  46. Python distinguishes between files opened in binary and text modes,
  47. even when the underlying operating system doesn't. Files opened in
  48. binary mode (appending 'b' to the mode argument) return contents as
  49. bytes objects without any decoding. In text mode (the default, or when
  50. 't' is appended to the mode argument), the contents of the file are
  51. returned as strings, the bytes having been first decoded using a
  52. platform-dependent encoding or using the specified encoding if given.
  53. 'U' mode is deprecated and will raise an exception in future versions
  54. of Python. It has no effect in Python 3. Use newline to control
  55. universal newlines mode.
  56. buffering is an optional integer used to set the buffering policy.
  57. Pass 0 to switch buffering off (only allowed in binary mode), 1 to select
  58. line buffering (only usable in text mode), and an integer > 1 to indicate
  59. the size of a fixed-size chunk buffer. When no buffering argument is
  60. given, the default buffering policy works as follows:
  61. * Binary files are buffered in fixed-size chunks; the size of the buffer
  62. is chosen using a heuristic trying to determine the underlying device's
  63. "block size" and falling back on `io.DEFAULT_BUFFER_SIZE`.
  64. On many systems, the buffer will typically be 4096 or 8192 bytes long.
  65. * "Interactive" text files (files for which isatty() returns True)
  66. use line buffering. Other text files use the policy described above
  67. for binary files.
  68. encoding is the name of the encoding used to decode or encode the
  69. file. This should only be used in text mode. The default encoding is
  70. platform dependent, but any encoding supported by Python can be
  71. passed. See the codecs module for the list of supported encodings.
  72. errors is an optional string that specifies how encoding errors are to
  73. be handled---this argument should not be used in binary mode. Pass
  74. 'strict' to raise a ValueError exception if there is an encoding error
  75. (the default of None has the same effect), or pass 'ignore' to ignore
  76. errors. (Note that ignoring encoding errors can lead to data loss.)
  77. See the documentation for codecs.register or run 'help(codecs.Codec)'
  78. for a list of the permitted encoding error strings.
  79. newline controls how universal newlines works (it only applies to text
  80. mode). It can be None, '', '\n', '\r', and '\r\n'. It works as
  81. follows:
  82. * On input, if newline is None, universal newlines mode is
  83. enabled. Lines in the input can end in '\n', '\r', or '\r\n', and
  84. these are translated into '\n' before being returned to the
  85. caller. If it is '', universal newline mode is enabled, but line
  86. endings are returned to the caller untranslated. If it has any of
  87. the other legal values, input lines are only terminated by the given
  88. string, and the line ending is returned to the caller untranslated.
  89. * On output, if newline is None, any '\n' characters written are
  90. translated to the system default line separator, os.linesep. If
  91. newline is '' or '\n', no translation takes place. If newline is any
  92. of the other legal values, any '\n' characters written are translated
  93. to the given string.
  94. If closefd is False, the underlying file descriptor will be kept open
  95. when the file is closed. This does not work when a file name is given
  96. and must be True in that case.
  97. A custom opener can be used by passing a callable as *opener*. The
  98. underlying file descriptor for the file object is then obtained by
  99. calling *opener* with (*file*, *flags*). *opener* must return an open
  100. file descriptor (passing os.open as *opener* results in functionality
  101. similar to passing None).
  102. open() returns a file object whose type depends on the mode, and
  103. through which the standard file operations such as reading and writing
  104. are performed. When open() is used to open a file in a text mode ('w',
  105. 'r', 'wt', 'rt', etc.), it returns a TextIOWrapper. When used to open
  106. a file in a binary mode, the returned class varies: in read binary
  107. mode, it returns a BufferedReader; in write binary and append binary
  108. modes, it returns a BufferedWriter, and in read/write mode, it returns
  109. a BufferedRandom.
  110. It is also possible to use a string or bytearray as a file for both
  111. reading and writing. For strings StringIO can be used like a file
  112. opened in a text mode, and for bytes a BytesIO can be used like a file
  113. opened in a binary mode.
  114. [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即可看到这两个特殊目录。

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

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

以下面的目录结构为例

  1. .
  2. ├── a
  3. ├── a1
  4. ├── app.py
  5. └── test.txt
  6. └── a2
  7. └── b
  8. ├── b1
  9. └── b1.txt
  10. └── b2

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

同级目录文件访问:

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

直接填写文件名

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

执行结果如下:

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

以【.】目录相对定位

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

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

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

跨目录访问文件:

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

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

看代码!

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

输出结果:

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

3.1.2 绝对路径

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

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

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

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

  1. # 读文件
  2. f = open(file="/home/zsm/python14/a/a1/test.txt", mode="r")
  3. print(f.read())
  4. 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零基础快速入门系列》快速导航:

  • 【Python零基础入门笔记 | 01】 人工智能序章:开发环境搭建Anaconda+VsCode+JupyterNotebook(零基础启动)
  • 【Python零基础入门笔记 | 02】一文快速掌握Python基础语法
  • 【Python零基础入门笔记 | 03】AI数据容器底层核心之Python列表
  • 【Python零基础入门笔记 | 04】为什么内存中最多只有一个“Love“?一文读懂Python内存存储机制
  • 【Python零基础入门笔记 | 05】Python只读数据容器:列表List的兄弟,元组tuple
  • 【Python零基础入门笔记 | 06】字符串、列表、元组原来是一伙的?快看序列Sequence
  • 【Python零基础入门笔记 | 07】成双成对之Python数据容器字典
  • 【Python零基础入门笔记 | 08】无序、不重复、元素只读,Python数据容器之集合
  • 【Python零基础入门笔记 | 09】高级程序员绝世心法——模块化之函数封装
  • 【Python零基础入门笔记 | 10】类的设计哲学:自然法则的具现
  • 【Python零基础入门笔记 | 11】函数、类、模块和包如何构建四级模块化体系
  • 【Python零基础入门笔记 | 12】程序员为什么自嘲面向Bug编程?
  • 【Python零基础入门笔记 | 13】面对海量数据,如何优雅地加载数据?请看迭代器与生成器

写在末尾:

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


本文转载自: https://blog.csdn.net/RobotFutures/article/details/125647298
版权归原作者 i机器未来 所有, 如有侵权,请联系我们删除。

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

还没有评论