Fourteen self-study notes for programming novices (python office automation to create, copy, and move files and folders)

Table of Contents of Series Articles

Thirteen self-study notes for programming novices (python office automation reading and writing files)

Self-study notes for programming beginners 12 (Introduction to Python crawler 4, Selenium usage example 2)

Self-study Notes for Programmers Novice 11 (Introduction to Python Crawler 3: Use of Selenium + Detailed Examples)

Self-study notes for programming beginners 10 (Introduction to python crawler 2 + detailed explanation of example code) 

 Self-study Notes 9 for Programmers (Introduction to Python Crawler + Detailed Code Explanation) 

Table of contents

Table of Contents of Series Articles

Article directory

Preface

1. os.scandir()

2. Temporary files and temporary folders

1. Create temporary files

 2. Create a temporary folder

3. Create folders and multi-layer folders

 1. Create a folder

 2. Create multi-layer folders

 4. Copy files and folders

 5. Move files and folders

Summarize


Preface

In the self-study note 1, I have already learned how to read and write files, which is the basis of learning. Now I am starting to learn office automation, and I need to study in depth.


1. os.scandir()

os.scandir() is a function in Python that gets an iterator of directories in a file system. It can traverse all entries in the specified directory, including files and subdirectories. The os.scandir() method returns an os.DirEntry iterator object, which is very lightweight and convenient, and can tell you the path of the iterated file.

 Using the os.scandir() method is more efficient than using the os.walk() method because the os.walk() method traverses the entire directory tree, while the os.scandir() method only traverses the specified directory.

 The iterator object returned by os.scandir() needs to be called using a for loop. Let’s use the code to see what is output:

import os
for file in os.scandir():
   print(file)

 The output is:

<DirEntry 'Dome.py'>

<DirEntry 'new.xls'>

<DirEntry 'Table merge.py'>

 After all files in the directory have been output, we can continue to call the stat() method to view the attributes of the files. code show as below:

import os
for file in os.scandir():
    print(file.stat())

 The output is:

 

 It can be seen that the content includes the size of the file, as well as the creation time, modification time and access time of the file. Let’s try the creation time of the output file:

import os
for file in os.scandir():
    print(file.stat().st_ctime)

The time is indeed output, but it is a time that we cannot understand:

1688730869.341578

1687012891.5642674

1687068649.1589775

 Below we use datetime to change the time format to the time format used in our daily life:

import os
import datetime
for file in os.scandir():
     print(datetime.datetime.fromtimestamp(file.stat().st_ctime))

The output is:

2023-07-07 19:54:29.341578

2023-06-17 22:41:31.564267

2023-06-18 14:10:49.158978

2. Temporary files and temporary folders

 tempfile() is a module in the Python standard library used to create temporary files and directories. It can be used across platforms, including Windows, Linux, macOS, etc. This module provides four functions: TemporaryFile(), NamedTemporaryFile(), TemporaryDirectory() and SpooledTemporaryFile(). These functions have automatic cleaning functions and can be used as context managers. Among them, TemporaryFile() and NamedTemporaryFile() are the two most common functions. They can both create a temporary file object. When the file object is closed, the temporary file will be automatically deleted. TemporaryDirectory() and SpooledTemporaryFile() are functions used to create temporary directories and buffer files.

1. Create temporary files

Let's look at a simple code to learn how to create a temporary file: 

from tempfile import TemporaryFile
with TemporaryFile('w+') as file:
    file.write('我是一个临时文件')
    print(file.name)
    file.seek(0)
print(file.readlines())

 The output is:

C:\Users\ADMINI~1\AppData\Local\Temp\tmpdms710yj

['I am a temporary file']

 It can be seen that the address of this file is "C:\Users\ADMINI~1\AppData\Local\Temp\tmpdms710yj". file.seek(0) means to move the cursor to the beginning position and then read, We can try whether it is reading from the cursor position, such as the following code:

from tempfile import TemporaryFile
with TemporaryFile('w+') as file:
    file.write('我是一个临时文件')
    print(file.name)
    file.seek(4)
    print(file.readlines())

 According to what we said above, reading should start from the fourth byte, and the output result is

C:\Users\ADMINI~1\AppData\Local\Temp\tmp82yzs4dc

['a temporary file']

 We can see that the address of the file has changed, indicating that it is indeed a temporary file. The previous file has been deleted. At the same time, a Chinese character is two bytes, so "I am" is gone. Reading from the back, the content is "a temporary file" .

 2. Create a temporary folder

Let's take a look at how to create a temporary folder. The code is as follows:

from tempfile import TemporaryDirectory
with TemporaryDirectory() as t:
    print(t)

The output is:

C:\Users\ADMINI~1\AppData\Local\Temp\tmpcy74dyo0

Obviously, this is the location of the temporary folder. Let's run the program again. In theory, the name of the folder will change and a new folder will be created. Let's try it. The output is:

C:\Users\ADMINI~1\AppData\Local\Temp\tmpx_kr8bau

3. Create folders and multi-layer folders

 1. Create a folder

 First use mkdir to create a folder, the code is as follows

Import os
os.mkdir(‘文件夹1’)

 At this time, we created a folder named "Folder 1". Note here that you cannot create an existing folder, and the system will report an error.

 2. Create multi-layer folders

 In Python, you can use the `os.makedirs()` function to create folders and multi-layer folders. This function can recursively create multi-level directories. If the directory already exists, no error will be reported.

 The following is sample code for creating folders and multi-layer folders using the `os.makedirs()` function:

import os

# 创建一个名为"my_folder"的文件夹
if not os.path.exists("my_folder"):
    os.makedirs("my_folder")

# 在"my_folder"文件夹下创建一个名为"sub_folder"的子文件夹
if not os.path.exists("my_folder/sub_folder"):
    os.makedirs("my_folder/sub_folder")

# 在"my_folder/sub_folder"文件夹下创建一个名为"grand_sub_folder"的子文件夹
if not os.path.exists("my_folder/sub_folder/grand_sub_folder"):
    os.makedirs("my_folder/sub_folder/grand_sub_folder")

 In the above code, we first check if a folder named "my_folder" exists and if not, create it using `os.makedirs()` function. Then, we create a subfolder named "sub_folder" under the "my_folder" folder and a subfolder named "grand_sub_folder" within it. Note that when creating a multi-layer folder, you need to use a relative path or an absolute path to specify the name of the folder to be created.

In fact, you can directly create the innermost folder, the code is as follows

Import os
os.makedirs(‘第一层文件夹/第二层文件夹/第三层文件夹’)

In this way, the first-level folder, the second-level folder, and the third-level folder are created directly.

 4. Copy files and folders

 In Python, we can copy files and folders using functions in the `shutil` module. For files, we can use the `shutil.copy()` function to copy the file, which accepts two parameters: source file path and target file path. For folders, we can use the `shutil.copytree()` function to copy the entire folder, which also accepts two parameters: source folder path and destination folder path.

 The following is a sample code that demonstrates how to copy files and folders using functions in the `shutil` module:

import shutil

# 复制文件
shutil.copy('source_file.txt', 'destination_file.txt')

# 复制文件夹
shutil.copytree('source_folder', 'destination_folder')

 In the above code, we first imported the `shutil` module. We then use the `shutil.copy()` function to copy the file named "source_file.txt" to the same location and rename the new file as "destination_file.txt". Next, we use the `shutil.copytree()` function to copy the folder named "source_folder" to a new folder named "destination_folder". Please note that if the target folder does not exist, it will be created automatically, and an error will be reported if the target folder already exists.

 5. Move files and folders

 In Python, we can move files and folders using functions in the `shutil` module. For files, we can use the `shutil.move()` function to move the file, which accepts two parameters: source file path and target file path. For folders, we can use the `shutil.rmtree()` function to first delete the original folder, then use the `shutil.copytree()` function to copy the folder to a new location, and finally use the `os.remove()` function to delete it. original folder.

 The following is a sample code that demonstrates how to use functions in the `shutil` module to move files and folders:

import shutil
import os

# 移动文件
shutil.move('source_file.txt', 'destination_file.txt')

# 移动文件夹
src_folder = 'source_folder'
dst_folder = 'destination_folder'
if os.path.exists(src_folder):
    shutil.rmtree(src_folder)
shutil.copytree(src_folder, dst_folder)
os.remove(src_folder)

 In the above code, we first imported the `shutil` and `os` modules. We then use the `shutil.move()` function to move the file named "source_file.txt" to a new file named "destination_file.txt". Next, we define the source folder path `src_folder` and the target folder path `dst_folder`, and check whether the source folder exists. If it exists, use the `shutil.rmtree()` function to delete it. Then, we use the `shutil.copytree()` function to copy the source folder to the destination folder. Finally, we remove the source folder using the `os.remove()` function.


Summarize

none

Guess you like

Origin blog.csdn.net/m0_49914128/article/details/132841778