python文件的基础操作

93 阅读3分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第5天,点击查看活动详情


大家好,我是芒果,一名非科班的在校大学生。对C/C++、数据结构、Linux及MySql、算法等领域感兴趣,喜欢将所学知识写成博客记录下来。 希望该文章对你有所帮助!如果有错误请大佬们指正!共同学习交流

作者简介:


本节内容:

掌握文件基本操作 掌握文件系统基本操作 能够结合之前学习的知识, 写出一些实用程序.


文件的基础操作

打开/关闭文件

内建函数open, 能够打开一个指定路径下的文件, 返回一个文件对象.

open最常用的有两个参数, 第一个参数是文件名(绝对路径或者相对路径), 第二个是打开方式

  • 'r'/'w'/'a'/'b',表示读(默认)/写/追加写/二进制.
  • 注意:打开文件一定要记得关闭
a = open('Z:/test.txt','r') #注意不是反斜杠,Z盘要大写
a.close()   #关闭文件

关于内建函数:

我们反复遇到了 "内建函数" 这个词. 内建函数其实是包含在 builtins 这个模块中的一些函数.

builtins 这个模块Python解释器会自动包含.

使用 dir(builtins) 可以看到Python中一共有哪些内建函数

print(dir(__builtins__))
#执行结果:
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'ModuleNotFoundError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError', '__build_class__', '__debug__', '__doc__', '__import__', '__loader__', '__name__', '__package__', '__spec__', 'abs', 'all', 'any', 'ascii', 'bin', 'bool', 'breakpoint', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']

关于文件对象:

我们学习C语言知道 FILE* , 通过 FILE* 进行文件读写操作.

我们学习Linux时又知道, FILE 结构中其实包含了文件描述符*, 操作系统是通过文件描述符来对文件操作 的

Python的文件对象, 其实也包含了文件描述符, 同时也包含了这个文件的一些其他属性. 本质上也是通过文件描述符完成对文件的读写操作.

既然文件对象包含了文件描述符, 我们知道, 一个进程可操作的文件描述符的数目是有上限的. 因此对于 完了的文件描述符要及时关闭.


当文件对象被垃圾回收器销毁时, 也会同时释放文件描述符.

如果文件打开失败(例如文件不存在), 就会执行出错

a = open('Z:\XXX','r')
#执行结果:
FileNotFoundError: [Errno 2] No such file or directory: 'Z:\XXX'

\