A few lines of Python code to handle file operations

Life is short, I use Python.

As we all know, Python can do anything but can't have children.

In daily work, dealing with some files, usually only a few lines of code can be done with Python. Read and modify files in batches. Rename folders and files in a unified format, etc. All can be done with Python one-click.

This blog summarizes some commonly used Python text operations. If there are any omissions, please comment and let us know.

If this article is helpful to you, just click like, follow, and bookmark.

File reading and writing

open() method

The open() method can be used to read and write the text, it will return a File object, when calling, generally need to pass in two parameters

  • file: Name file (absolute path or relative path will do).
  • mode: The mode of access. Commonly used
    • w: Write mode, if the file does not exist, it will create one, if it exists, delete the original content. Edit from scratch.
    • w+: Read and write mode. If the file does not exist, one will be created, if it exists, the original content will be deleted. Edit from scratch.
    • r: Read only mode. Read the file from the beginning of the file.
    • a: Append mode. If the file already exists, start editing from the end of the file, if not, create one.
    • a+: Read and write mode. If the file already exists, start editing from the end of the file, if not, create one.
    • If you need to read binary files or write files in binary mode. Then add a'b' after the above pattern. For example: wb,wb+,rb,ab,ab+.

If there is Chinese in the opened file, garbled characters may appear. At this time, you have to use the third parameter to specify the encoding format of the file opening

  • encoding: Fill in according to the encoding of the file.

Get a file object

file=open('filename','r')

So we get a file object. Then if you want to get the contents of the file, you can use a for loop to read each line

for line in file:
    print(line)

To read a specified number of characters, you can use the read() method

chars=file.read(20) # 从文件读取指定的字节数,如果未给定或为负则读取所有。

Set the position of the file pointer, you can use the seek() method

  • offset: offset, how many bytes need to be cheaper
  • whence: The default value is 0. Indicates where the offset starts.
file.seek(00)

To write to a file, you can use the write() method

s="jiangxiaoju"
file.write(s)

If you want to write multiple strings at the same time, you can use writelines.

strs=['aaaa\n','bbbb']
file.writelines(strs) # 若需要换行,则需要在字符串后面加上换行符

File/directory operations

File manipulation is also a very powerful function. Python provides a lot of methods, covering almost all possible operations. Here are a few commonly used bloggers, and you can refer to the methods listed here for details. Python OS file/directory method

The file operations are all in osthis package.

First import the os package

import os

Judgment of authority

Confirm whether there are certain operation permissions, but generally do not consider for Windows users. Only a multi-user system like Linux needs to determine whether it has certain permissions. os.access(path,mode).

  • path: The path to determine the permissions.
  • mode: There are four parameters to os.F_OKdetermine whether the path exists. os.R_OKDetermine whether it is readable. os.W_OKDetermine whether it is writable. os.X_OKDetermine whether it is executable.

Switch working directory, return to current working directory

This operation is very similar to the dos command

os.chdir(path)# path 就是要切换的新路径
os.getcwd()

Create folder

To os.mkdir()create a folder, two parameters are required

  • path: the directory or folder name created
  • mode: Set permission digital mode. The default is 0777 (octal)
os.mkdir('/tmp/test') #以Linux系统上为例。 

Rename file or directory

Used os.rename(). Two parameters are required

  • src: The name of the directory to be modified
  • dst: modified directory name
os.rename('test','test2')

Get all files or folder names in the specified folder

Use os.listdir()method

dirs=os.listdir('./')
for file in dirs:
    print(file)

os.path() module

This module is used to obtain file attributes.

Get absolute path

os.path.abspath(path)

Determine whether the path exists

os.path.exists(path)

Get file name

os.path.basename(path)

Determine whether it is a file

os.path.isfile(path)

Determine whether it is a directory

os.path.isdir(path)

Path stitching

Combine directory and file name into one directory

os.path.join('/test','a.txt')

For the enumerated methods, please refer to the Python os.path() module

Guess you like

Origin blog.csdn.net/qq_43058685/article/details/107967385