轉移文件到單獨的文件夾
瀏覽:2391
功能是把當前文件夾下allFiles的文件轉移到相應的文件夾中,os.getcwd()不能用換了一個
import os
import shutil
# 定義 allFiles 文件夾路徑
#source_folder = os.path.join(os.getcwd(), 'allFiles')
current_file_path = os.path.abspath(__file__)
current_directory = os.path.dirname(current_file_path)
source_folder = os.path.join(current_directory, 'allFiles')
print(source_folder)
# 檢查 allFiles 文件夾是否存在
if not os.path.exists(source_folder):
print("錯誤:{} 文件夾不存在。".format(source_folder))
else:
# 遍歷 allFiles 文件夾中的所有文件
for filename in os.listdir(source_folder):
file_path = os.path.join(source_folder, filename)
# 檢查是否為文件
if os.path.isfile(file_path):
# 提取文件名(不包含擴展名)
folder_name = os.path.splitext(filename)[0]
# 創建與文件名相同的目標文件夾
target_folder = os.path.join(source_folder, folder_name)
if not os.path.exists(target_folder):
os.makedirs(target_folder)
# 移動文件到目標文件夾
try:
shutil.move(file_path, os.path.join(target_folder, filename))
print("已將 {} 移動到 {}。".format(filename, target_folder))
except Exception as e:
print("移動 {} 時出錯:{}".format(filename, e))
cmd /k C:\Python34\python.exe "moveToFolder.py" & ECHO. & PAUSE & EXIT
技術鄰APP
工程師必備
工程師必備
- 項目客服
- 培訓客服
- 平臺客服
TOP




















