python怎么处理文件夹里的文件

在Python中,可以使用os模块来处理文件夹里的文件。以下是一些常见的方法:

获取文件夹中的文件列表:

import os

folder_path = '/path/to/folder'
file_list = os.listdir(folder_path)

遍历文件夹中的文件:

import os

folder_path = '/path/to/folder'
for file_name in os.listdir(folder_path):
    file_path = os.path.join(folder_path, file_name)
    # 进行相应的处理

检查文件是否存在:

import os

file_path = '/path/to/file'
if os.path.exists(file_path):
    # 文件存在
else:
    # 文件不存在

创建文件夹:

import os

folder_path = '/path/to/folder'
os.makedirs(folder_path, exist_ok=True)

复制文件:

import shutil

source_file = '/path/to/source_file'
destination_folder = '/path/to/destination_folder'
shutil.copy(source_file, destination_folder)

删除文件:

import os

file_path = '/path/to/file'
os.remove(file_path)

请根据具体需求选择适当的方法来处理文件夹中的文件。

阅读剩余
THE END