温馨提示×

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

小亿
89
2023-11-14 10:22:26
栏目: 编程语言

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

  1. 获取文件夹中的文件列表:
import os

folder_path = '/path/to/folder'
file_list = os.listdir(folder_path)
  1. 遍历文件夹中的文件:
import os

folder_path = '/path/to/folder'
for file_name in os.listdir(folder_path):
    file_path = os.path.join(folder_path, file_name)
    # 进行相应的处理
  1. 检查文件是否存在:
import os

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

folder_path = '/path/to/folder'
os.makedirs(folder_path, exist_ok=True)
  1. 复制文件:
import shutil

source_file = '/path/to/source_file'
destination_folder = '/path/to/destination_folder'
shutil.copy(source_file, destination_folder)
  1. 删除文件:
import os

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

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

0