Retrieve .py in the qpython folder

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 folder

Search .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:

  1. Retrieve files /storage/emulated/0/qpythonunder the folder .py.
  2. Generate a new file name + number + original file name for each file.
  3. 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.pyAll 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 .pyfiles 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.

Insert image description here
This code involves some common Python file and folder manipulation methods, such as:

  1. os.path.join(): Combine multiple paths into one suitable for the current operating system.
  2. os.listdir(): Returns the name list of all files and folders under the specified path.
  3. os.path.exists(): Check whether the specified path exists.
  4. os.makedirs(): Create all directories under the specified path.

Additionally, the code uses methods shutilfrom Python's module copy()to copy files. This method not only copies files, but also copies folders recursively.
Insert image description here

Insert image description here

Guess you like

Origin blog.csdn.net/weixin_73675558/article/details/133496973