Python中的os库是一个非常功能强大的一个内置库 使用 import os 来导入 以下是一些os库基本用法:
- os.chdir (#目录名) 切换至括号内的目录
- os.getcwd () 用于获取当前目录
- 可以搭配print()命令用于输出当前目录
- os.path.exists(#path)用于检测文件或者目录是否存在,避免不必要的麻烦
- os.remove(#file)用于删除文件(不可恢复,请勿删除目录)
- os.rename(#path)重命名文件或者目录
- os.rmdir(#path)用于删除空的目录(仅用于删除空的目录,避免不必要的麻烦)
- os.listdir(#path)用于列出目录(请勿填写文件名)
- os.mkdir(#path)用于创建目录(请勿用于创建文件)
可以通过内置库和os库的结合来制作一些程序 这里放一个文件资源管理器: import os
- def exp():
-
print("DIR:", os.getcwd())
while True: cmd_input = input(f"\n{os.getcwd()} > ").strip() if not cmd_input: continue cmd_list = cmd_input.split(maxsplit=2) cmd = cmd_list[0].lower() if cmd == "cd": if len(cmd_list) < 2: print("Bad command or file name") continue target_dir = cmd_list[1] try: os.chdir(target_dir) print("DIR", os.getcwd()) except Exception as e: print("error:", str(e)) elif cmd == "dir": try: items = os.listdir(os.getcwd()) for item in items: item_path = os.path.join(os.getcwd(), item) if os.path.isdir(item_path): print(f"【DIR】{item}") else: print(f" {item}") except Exception as e: print("error:", str(e)) elif cmd == "new": if len(cmd_list) < 3: print("Bad command or file name") continue obj_type = cmd_list[1].lower() obj_name = cmd_list[2] obj_path = os.path.join(os.getcwd(), obj_name) try: if obj_type == "file": open(obj_path, "w").close() print(f"已新建文件:{obj_name}") elif obj_type == "dir": os.mkdir(obj_path) print(f"已新建目录:{obj_name}") else: print("Bad command or file name") except Exception as e: print("Bad command or file name") elif cmd == "del": if len(cmd_list) < 2: print("Bad command or file name") continue target_path = os.path.join(os.getcwd(), cmd_list[1]) try: if os.path.isfile(target_path): os.remove(target_path) print(f"已删除文件:{cmd_list[1]}") elif os.path.isdir(target_path): os.rmdir(target_path) print(f"已删除目录:{cmd_list[1]}") else: print("Bad command or file name") except Exception as e: print("error:", str(e)) file_path = os.path.abspath(CMD) elif os.path.exists(cmd): try: os.startfile(cmd) # 用系统默认程序打开文件 except: print(f"错误:{cmd} 文件不存在!") elif cmd == "exit": print("Done") break else: print("Bad command or file name")exp()
- 别忘了调用函数
-