python写一段按照文件类型进行桌面整理的代码
时间: 2023-06-01 16:07:48 浏览: 105
好的,以下是一段 Python 代码,可以按照文件类型对桌面进行整理:
```python
import os
import shutil
def organize_desktop():
# 获取桌面路径
desktop_path = os.path.join(os.path.expanduser("~"), "Desktop")
# 文件类型对应的文件夹名称
file_types = {
"images": ["png", "jpg", "jpeg", "gif"],
"documents": ["doc", "docx", "pdf", "txt"],
"videos": ["mp4", "avi", "mov", "mkv"],
"music": ["mp3", "wav", "flac", "m4a"],
"archives": ["zip", "rar", "7z", "tar", "gz"],
"executables": ["exe", "dmg", "pkg", "msi"]
}
# 创建文件夹
for folder_name in file_types.keys():
folder_path = os.path.join(desktop_path, folder_name)
if not os.path.exists(folder_path):
os.mkdir(folder_path)
# 遍历桌面文件
for file in os.listdir(desktop_path):
file_path = os.path.join(desktop_path, file)
# 如果是文件夹或者不识别的文件类型,则不处理
if os.path.isdir(file_path) or "." not in file:
continue
# 获取文件类型
file_extension = file.split(".")[-1].lower()
# 将文件移动到对应的文件夹
for folder_name, extensions in file_types.items():
if file_extension in extensions:
folder_path = os.path.join(desktop_path, folder_name)
shutil.move(file_path, folder_path)
break
if __name__ == '__main__':
organize_desktop()
```
这段代码会在桌面上创建几个文件夹,然后将相应类型的文件移动到对应的文件夹中。注意,这段代码可能会删除桌面上的文件,请谨慎运行。
阅读全文