Python file and directory operation code summary

Foreword

In python, a file object is built-in, and file operations can be realized through some built-in methods, such as the open() method to create a file object, and the write() method to write content to the file.

1. Basic file operation

1. Create and open files

To manipulate a file, you must first create or open the specified file and create a file object, which can be achieved through the built-in function open().

file =open(file_name[,mode[,buffering]])'''
file_name :File name to be created or opened
mode: Used to specify how the file is opened
'''

Parameter value table of mode parameter

Mode Description
r Open the file as read-only. The pointer of the file will be placed at the beginning of the file. This is the default mode.
rb Open a file in binary format for read-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. If the file already exists, open the file and start editing from the beginning, that is, the original content will be deleted. If the file does not exist, create a new file.
wb Open a file in binary format for writing only. If the file already exists, open the file and start editing from the beginning, that is, the original content will be deleted. If the file does not exist, create a new file.
w+ Open a file for reading and writing. If the file already exists, open the file and start editing from the beginning, that is, the original content will be deleted. If the file does not exist, create a new file.
wb+ Open a file in binary format for reading and writing. If the file already exists, open the file and start editing from the beginning, that is, the original content will be deleted. 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. In other words, the new content will be written after the existing content. If the file does not exist, create a new file 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. In other words, the new content will be written after the existing content. If the file does not exist, create a new file 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. When the file is opened, it will be 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.

note

When opening a file with the open() function, GBK encoding is used by default. If you want to use other encoding methods, you need to add the encoding parameter

file = open(‘./text.txt’,’a+’,encoding=’utf-8′)

Need to use the original file encoding method to open, otherwise an error will be reported

2. Close file

After opening the file, it needs to be closed in time to avoid unnecessary damage to the file. You can use the built-in function close().

file = open(‘./text.txt’,’a+’)
file.close()

Note

The close() function first refreshes the information that has not been written in the buffer, writes it to the file, and then closes the file to protect the file.

3. Write to file

grammar

file = write(string)

demo

# open a file
file =open('./text.txt','a+')
# Write file
file =write('Live up to code, live up to Qing')
# Close file
file.close()

Note:

When writing the file again, inject the mode in which the file was opened, otherwise the original data will be overwritten.

4. Read file

The prerequisite for reading the file is that when the file is opened, the specified open mode is r (read-only) or r+ (read-write). Otherwise, an exception will be thrown.

(1) Read the specified characters

file.read([size])

size: Used to specify the number of characters to be read, if omitted, all content will be read at once.

(2) Read one line

file.readline()

This method is used to read a line of text

(3) Read all rows

file.readlins()

2. Directory operations

Python has a built-in os module and submodule os.path for manipulating directories or files.

Directory-related functions provided by the os module

Function Description
getcwd() Return the current working directory
listdir(path) Return file and directory information under the specified path
mkdir(path[,mode]) Create directory
makedirs(path/path2…..) Create multi-level directories
rmdir(path) Delete directory
removedirs(/path1/path2...) Remove multi-level directories
chdir(path) Set path to the current working directory
walk(top[,topdown[,onerror]) traverse
access(path,accessmode) Get whether the specified file has a certain permission (accessmode is equal to R_OK (read), W_OK (write), X_OK (execute), F_OK (exist)), if there is a specified permission, return 1 , Otherwise return 0.
chmod(path,mode) Modify the access permissions of the file specified by path
remove(path) Remove the specified file path
rename(src,dst) Rename the file or directory src to dst
stat(path) Returns information about the file specified by path

The os.path module provides functions related to directories

Function Description
abspath(path) Used to obtain the absolute path of a file or directory
exists(path) Used to determine whether the directory or file exists, if it exists, it returns True, otherwise it returns False
join(path,name) Join the directory with the directory or file name
splitext() Separate file name and extension
split(path) Split path and file name
basename(path) Extract file name from a directory
dirname(path) Extract the file path from a path, not including the file name
isdir(path) Used to determine whether the path is valid

demo —— Get the current working directory

import os
print(os.getcwd())

demo —— Determine whether the directory exists

import os
print(os.path.exists(“c:\demo”))

Note

Because exists() is provided by the submodule of os, you need to add a prefix, os.path

demo —— Create a first-level directory

import os
path ="c://demo"
# If the directory to be created already exists, an exception will be thrown, first determine whether the directory to be created exists
if not os.path.exists(path):
	os.mkdir(path)else:print('The directory already exists')

Note

The directory created by mkdir(path) is a first-level directory. If the last-level parent directory in the passed path does not exist, an exception will be thrown.

demo —— Create a multi-level directory

import os
os.makedirs(“C:\demo1\demo2\…”)

demo —— delete directory

import os
path ="C:\demo1\demo2"
# Determine the directory to be deleted, if it does not exist, it will throw a problem
if os.path.exists(path):
	os.rmdir("C:\demo1\demo2") #Deleted the demo2 file
	print("Directory deleted successfully!")else:print("The directory does not exist")

Note:

The rmdir() function can only delete empty directories. If they are not empty, they cannot be deleted. You can delete non-empty directories with the following code.

import shutil
shutil.rmtree("C:\demo\text")

demo-traverse directories

The return value of os.walk() is a tuple generator object containing three elements (dirpath, dirnams, filenames).

dirpath: is a string representing the path currently traversed

dirnames: is a list representing the subdirectories contained in the current path

filenames: is also a list of files in the current directory

os.walk(top,[topdown][,onerror][,followlinks])'''
top:Used to specify the directory to be traversed
topdown:Optional parameter, used to specify the order to be traversed, if True (default), it means traversal from top to bottom, if False,Means from childhood to top.
'''
import os
path ="C:\demo"
# root is the current root path, dirs contains the subdirectories under the path, files contains the two to five years under the subdirectories
for root,dirs,fles in os.walk(path,topdown=True):for name in dirs:print(os.path.join(root,name))for name in files:print(os.path.join(root.name))

demo-find whether a file exists in the current directory

import os
path ="C:\demo"
filename ="love.txt"for root,dirs,files in os.walk(path):for name in files:if filename== name:print(os.path.join(root,name))

The above is the whole content of this article, I hope it will be helpful to everyone's study.

Recommended Posts

Python file and directory operation code summary
Python automated operation and maintenance 2
Python automated operation and maintenance 1
Quick start Python file operation
Python file read and write operations
Python list comprehension operation example summary
Python file operation basic process analysis
Python handles operation code to execl
Python process and thread summary case analysis
Python process and thread summary case analysis
python_ file processing
Python and Go
Python basic summary
Python memory mapped file read and write method
python operation kafka
A brief summary of the difference between Python2 and Python3
Python introspection and reflection
Python processing json summary
[python] python2 and python3 under ubuntu
Python interview questions summary
Python operation SQLite database
Python advanced usage summary
Python SMS bombing code
Python operation yaml instructions
Python deconstruction and packaging