Password required
Retrieve the .py file number + original file name in the /storage/emulated/0/qpython folder: copy to /storage/emulated/0/qpython/py file/ Create if there is no folderSearch .py in the qpython folder and copy it to a separate path of the py file
According to this question list and steps, we need to complete the following tasks:
- Retrieve files
/storage/emulated/0/qpython
under the folder.py
. - Generate a new file name + number + original file name for each file.
- Copy each file to
/storage/emulated/0/qpython/py文件/
the directory. If the directory does not exist, you need to create it first.
The following is the specific code implementation:
import os
import shutil
# 源文件夹路径
src_folder = '/storage/emulated/0/qpython'
# 目标文件夹路径
dst_folder = '/storage/emulated/0/qpython/py文件'
# 创建目标文件夹
if not os.path.exists(dst_folder):
os.makedirs(dst_folder)
# 遍历源文件夹中的文件
for file_name in os.listdir(src_folder):
# 判断是否为.py文件
if file_name.endswith('.py'):
# 生成新文件名
new_file_name = f"{
len(os.listdir(dst_folder)) + 1}_{
file_name}"
# 构建源文件路径和目标文件路径
src_file_path = os.path.join(src_folder, file_name)
dst_file_path = os.path.join(dst_folder, new_file_name)
# 复制文件到目标文件夹
shutil.copy(src_file_path, dst_file_path)
Please note that the above code will
/storage/emulated/0/qpython
.py
All files in the folder are copied /storage/emulated/0/qpython/py文件
to the directory and renamed in the format of number + original file name. If the target folder does not exist, the code will create it first.
If you need to return results or further actions after the step is completed, modify it based on the final results.
This code scenario is a simple Python script that retrieves all .py
files in a specified folder, copies them to another folder, and renames them in the format of number + original file name. If the target folder does not exist, the code will create it first.
This code involves some common Python file and folder manipulation methods, such as:
os.path.join()
: Combine multiple paths into one suitable for the current operating system.os.listdir()
: Returns the name list of all files and folders under the specified path.os.path.exists()
: Check whether the specified path exists.os.makedirs()
: Create all directories under the specified path.
Additionally, the code uses methods shutil
from Python's module copy()
to copy files. This method not only copies files, but also copies folders recursively.