操作文件

Posted andypengx

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了操作文件相关的知识,希望对你有一定的参考价值。

open(filemode=‘r‘buffering=-1encoding=Noneerrors=Nonenewline=Noneclosefd=Trueopener=None)

Open file and return a corresponding file object. If the file cannot be opened, an OSError is raised.

file is either a string or bytes object giving the pathname (absolute or relative to 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 exclusive creation 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:

CharacterMeaning
‘r‘ open for reading (default)。读操作
‘w‘ open for writing, truncating the file first  打开文件进行写操作,如果文件已经存在,会清空其内容  
‘x‘

open for exclusive creation, failing if the file already exists  python3.5 新增加的模式,独占创建文件。如果文件已经存在,则创建失败。

‘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)  打开文件进行更新操作,也就是支持对文件进行读写操作。注意文件操作指针的位置。

read 和write操作都会移动当前文件的操作指针。例如write(‘haha‘),会覆盖当前指针所在位置后面的4个位置,这时指针也移动了4个位置。

read操作同样也会移动指针位置。

w+:

该模式依然是会在打开文件的同时清空文件的内容。请注意。

 

 

‘U‘ universal newlines mode (deprecated)

以上是关于操作文件的主要内容,如果未能解决你的问题,请参考以下文章

VSCode自定义代码片段15——git命令操作一个完整流程

VSCode 如何操作用户自定义代码片段(快捷键)

代码片段 - Golang 实现集合操作

Apollo Codegen 没有找到生成代码的操作或片段

VSCode自定义代码片段——.vue文件的模板

操作栏标签片段中的片段?