Python has packaged functions for opening and manipulating files. In this article, we will talk about the usage and differences of these methods.
open
The open() function is used to open a file. To create a file object,
open needs to be closed manually. If it is not closed, an exception will occur. It is generally used together with try-catch, so that it can be closed normally even if an exception occurs. Example usage
:
file = open(’test.txt’, ‘w’)
file.write(‘Hello, world!’)
file.close()
Way | meaning |
---|---|
r | Read-only can be omitted, if the file does not exist, an error will be reported |
w | Write only, if the file does not exist, delete the original content and write again when creating and opening the file, that is, overwrite |
a | Appending without read permission does not overwrite the original file, and directly appends to the end of the file |
+ | readable and writable |
r+ | Readable and writable, direct writing is to write from the beginning of the file. After read(), the file pointer jumps to the end of the file, and writes from the end. If the file does not exist, an error will be reported |
w+ | Readable and writable, if the file does not exist, create it, first delete the content of the original file, and then write |
a+ | Append read and write |
with open
with open will automatically call the close method, so we don't need to close it manually.
Usage example:
with open("test.txt","r") as file:
for line in file.readlines():
print(line.strip())# 把末尾的’\n’删掉
The "r" in the above code represents the opening method, and the following are all the opening methods and their meanings:
open method | meaning |
---|---|
r | Open the file read-only. The file pointer will be placed at the beginning of the file. This is the default mode . |
rb | Open a file in binary format for reading only. The file pointer will be placed at the beginning of the file. This is the default mode. |
r+ | Open a file for reading and writing. The file pointer will be placed at the beginning of the file. |
rb+ | Open a file in binary format for reading and writing. The file pointer will be placed at the beginning of the file. |
w | Open a file for writing only. Overwrite the file if it already exists. If the file does not exist, create a new file. |
wb | Open a file in binary format for writing only. Overwrite the file if it already exists. If the file does not exist, create a new file. |
w+ | Open a file for reading and writing. Overwrite the file if it already exists. If the file does not exist, create a new file. |
wb+ | Open a file in binary format for reading and writing. Overwrite the file if it already exists. If the file does not exist, create a new file. |
a | Open a file for appending. If the file already exists, the file pointer will be placed at the end of the file. That is, the new content will be written after the existing content. If the file does not exist, a new file is created for writing. |
ab | Open a file in binary format for appending. If the file already exists, the file pointer will be placed at the end of the file. That is, the new content will be written after the existing content. If the file does not exist, a new file is created for writing. |
a+ | Open a file for reading and writing. If the file already exists, the file pointer will be placed at the end of the file. The file will be opened in append mode. If the file does not exist, create a new file for reading and writing. |
ab+ | Open a file in binary format for appending. If the file already exists, the file pointer will be placed at the end of the file. If the file does not exist, create a new file for reading and writing. |
os.open、os.fdopen
os.open() creates an operating system-level file descriptor, and
os.fdopen() creates a file object from a file descriptor.
A file object is a Python class that contains a file descriptor, making files more convenient and less error-prone. They provide for example error handling, buffering, line-by-line reading, charset conversion, and shutdown when garbage collection.
File descriptors are low-level functions for working with files provided directly by the operating system kernel. A file descriptor is a small integer that identifies an open file in a table of open files kept by the kernel for each process. Many system calls accept file descriptors, but they are inconvenient to use, often requiring fixed-width buffers, multiple retries under certain conditions, and manual error handling.
The built-in open() takes a filename and returns a new Python file object. This is all you need in most cases.
os.open() takes a filename and returns a new file descriptor. This file descriptor can be passed to other low-level functions such as os.read() and os.write() or os.fdopen() as described below. You only need to do this when writing code that relies on OS-dependent APIs such as using the O_EXCL flag to open(2).
os.fdopen() takes an existing file descriptor - typically produced by a Unix system call such as pipe() or dup() - and generates a Python file object around it. Effectively, it converts the file descriptor into a full file object, which is useful when interfacing with C code, or just with APIs that create low-level file descriptors.
Built-in opening can be achieved using os.open() (to create a file descriptor) and os.fdopen() (to wrap it in a file object):
You can use os.fdopen and os.open instead of with open, this way you can specify the permission to open the file.
Usage example:
STAT_FLAGS = os.O_WRONLY
STAT_MODES = stat.S_IWUSR | stat.S_IRUSR
with os.fdopen(os.open(test_file, STAT_FLAGS, STAT_MODES), 'w') as fd:
test_file: the file to open
STAT_FLAGS: the way to open
STAT_MODES: the permission to open
The usage of os.open is as follows:
os.open(file, flags[, mode]);
flags specifies how to open.
flags – this parameter can be the following options, multiple use "|" separated, the flags parameter list:
parameter | meaning |
---|---|
os.O_RDONLY | open as read-only |
os.O_WRONLY | open for write only |
os.O_RDWR | open for reading and writing |
os.O_NONBLOCK | open without blocking |
os.O_APPEND | open as append |
os.O_CREAT | Create and open a new file |
os.O_TRUNC | Open a file and truncate it to zero length (must have write permission) |
os.O_EXCL | Returns an error if the specified file exists |
os.O_SHLOCK | Automatically acquire shared locks |
os.O_EXLOCK | Automatically acquire independent locks |
os.O_DIRECT | Eliminate or reduce caching effects |
os.O_FSYNC | write synchronously |
os.O_NOFOLLOW | Do not follow soft links |
mode specifies the permissions to open the file.
mode – This parameter can be the following options, multiple use "|" separated, mode parameter list:
parameter | meaning |
---|---|
stat.S_IXOTH | Other users have execute rights 0o001 |
stat.S_IWOTH | Other users have write permission 0o002 |
stat.S_IROTH | Other users have read permission 0o004 |
stat.S_IRWXO | 其他用户有全部权限(权限掩码)0o007 |
stat.S_IXGRP | 组用户有执行权限0o010 |
stat.S_IWGRP | 组用户有写权限0o020 |
stat.S_IRGRP | 组用户有读权限0o040 |
stat.S_IRWXG | 组用户有全部权限(权限掩码)0o070 |
stat.S_IXUSR | 拥有者具有执行权限0o100 |
stat.S_IWUSR | 拥有者具有写权限0o200 |
stat.S_IRUSR | 拥有者具有读权限0o400 |
stat.S_IRWXU | 拥有者有全部权限(权限掩码)0o700 |
stat.S_ISVTX | 目录里文件目录只有拥有者才可删除更改0o1000 |
stat.S_ISGID | 执行此文件其进程有效组为文件所在组0o2000 |
stat.S_ISUID | 执行此文件其进程有效用户为文件所有者0o4000 |
stat.S_IREAD | windows下设为只读 |
stat.S_IWRITE | windows下取消只读 |