Home  >  Article  >  Backend Development  >  Python’s top ten built-in file operations

Python’s top ten built-in file operations

WBOY
WBOYforward
2023-04-12 23:01:081771browse

Python’s top ten built-in file operations

There are many daily demands for batch processing of files, and it is often necessary to write scripts in Python to call external files!

This time I have compiled the top ten most commonly used file operation methods in Python, just use them directly!

1. Create and open files

If you want to operate a file, you need to first create or open the specified file and create a file object. Use the open() method to implement it. The syntax format is as follows:

file=open(filename[, mode[, buffering]])

Parameter description

  • file: the created file object
  • filename: the name of the file to be created or opened, single or double quotes are required bracketed. If the file to be opened is in the same directory as the current file, just write the file name directly; otherwise, specify the full path.
  • mode: optional parameter, used to specify the open mode, the default is read-only (i.e. r)
  • buffering: optional parameter, used to specify the cache mode of reading and writing files, the value is 0 means no caching, a value of 1 means caching; if greater than 1, it means the size of the buffer. Default caching mode.

By default, an exception will be displayed when opening a file that does not exist.

Python’s top ten built-in file operations

Solution:

  • Create a test.txt file in the current directory (the same directory as the executable file)
  • Call When using the open() method, specify the mode parameter value as w, w, a, a. If it does not exist, it will be created.

Full instructions for opening different modes.

Python’s top ten built-in file operations

Note: Open files use GBK encoding by default. When the opened file is not GBK encoded, an exception may be displayed. Solution: 1. Directly modify the encoding of the file. 2. Directly specify the encoding method to use when opening the file (recommended).

file=open('test.txt','r',encoding='utf-8')

2. Close the file

After opening the file, it needs to be closed in time to avoid occupying resources. Use the close() method to achieve this.

file.close()

Note: When using the close() method, the information that has not been written to the buffer will be flushed first, and then the file will be closed.

3. Use the with statement to open a file.

Opening a file needs to be closed in time. If you forget to close it, unexpected problems may occur. In addition, if an exception is displayed when opening the file, the file will not be closed in time. To avoid such problems, you can use the with statement provided by Python, which ensures that the opened file is closed after the with statement is executed, regardless of whether an exception is displayed. The basic syntax is as follows:

with expression as target:
 with-body

Parameter description:

  • expression: Specify the expression, which can be the open() method of opening a file.
  • target: used to specify a variable and save the result of expression to the variable.
  • with-body: used to specify the body of the with statement. It can be some related operation statements after executing the with statement, or it can be passed directly.

with open('test.txt','w') as file
pass

4. Write file content

The Python file object provides the write() method to write content to the file.

file.write(str)

Among them, file is the open file object; str is the string to be written. Note that writing requires write permission and specifies the opening mode as w (writable) or a (appendable)

Use the open() function and change the mode to w or a to open the file to create a file object . In w mode, old data will be overwritten and new data will be written. In a mode, new data can be added based on the original data.

5. Read data

After opening a file, in addition to writing or appending content to it, you can also read the content in the file. You need to know that the file opening mode is r (read) or r (read and write). There are three main situations:

  • Read the specified number of characters
  • file.read([size])——where size is an optional parameter. If omitted, all contents will be read at once.
  • Read one line
  • file.readline()——Read one line of data each time. When the file is large, read line by line. Pick.
  • Read all lines
  • file.readlines() - Returns a list of strings, each element is a line of the file.

with open('text.txt','r+',encoding='utf-8') as file:
print("读取前4个字符串")
print(file.read(4))
print("读取一行")
print(file.readline())
print("读取所有行")
print(file.readlines())

Note: If you want to read part of the content, you can first use the file object seek() method to move the file pointer to a new location, and then use read() method to obtain.

file.seek(offset[,whence]). Among them, the offset parameter is used to specify the number of moved strings, which occupies two characters per Chinese character; whence value is 0, it means counting from the beginning of the file. 1 means counting from the current position, 2 means counting from the end of the file, the default is 0.

6. Copying files

Python needs to use the copyfile() method of the shutil module to copy files.

shutil.copyfile(src,dst)

其中,src:要复制的源文件;dst:复制到的目标文件。

7、移动文件

Python移动文件需要使用shutil模块的move()方法。

shutil.move(src,dst)

其中,src:要移动的源文件;dst:移动到的目标文件。

8、重命名文件

Python重命名文件需要使用os模块的rename()方法。

os.rename(src,dst)

其中,src:指定要重命名的源文件;dst:指定重命名后文件。为确保正常执行,可以使用os.path模块的exists()方法判断要操作的文件是否存在。

9、删除文件

Python中删除文件需要使用os模块的remove()方法。

os.remove(path)

其中,path:指定要删除的文件路径,相对路径或绝对路径。

10、获取文件基本信息

文件本身包含一些信息,如文件最后一次访问时间、最后一次修改时间、文件大小等基本信息。通过os模块的stat()方法获取。

os.stat(path)

以上就是Python内置的十大常用的文件操作方法。

The above is the detailed content of Python’s top ten built-in file operations. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:51cto.com. If there is any infringement, please contact admin@php.cn delete