Python实现路径转换为计算机真实文件夹名称(非单纯大写)
如何将路径字符串转换为系统真实存在的文件夹名称
我需要将给定的路径字符串转换为计算机中真实存在的文件夹名称,而非仅对路径中的单词进行大写转换。
我的测试代码如下:
path = 'c:/users/student/pythonprojects' path = os.realname(path) # A function that converts it to the real path names print(path)
期望输出为:
>>> 'C:/Users/Student/PythonProjects'
实现方法
Python标准库中没有os.realname这个函数,针对Windows系统(你的示例路径是Windows格式),可以用以下两种方式实现需求:
方法一:调用Windows系统API
借助ctypes调用Windows原生API,直接获取路径的真实大小写格式:
import os import ctypes def get_real_path(path): # 先获取短路径,再通过短路径还原真实大小写的长路径 short_buf = ctypes.create_unicode_buffer(260) ctypes.windll.kernel32.GetShortPathNameW(path, short_buf, 260) short_path = short_buf.value long_buf = ctypes.create_unicode_buffer(32768) ctypes.windll.kernel32.GetLongPathNameW(short_path, long_buf, 32768) return long_buf.value # 测试 path = 'c:/users/student/pythonprojects' real_path = get_real_path(path) print(f">>> '{real_path}'")
方法二:逐层遍历验证路径
手动拆分路径的每一段,通过遍历目录获取真实的文件名/文件夹名:
import os def get_real_path(path): path = os.path.normpath(path) drive, rest = os.path.splitdrive(path) parts = [] current_dir = drive or os.getcwd() for part in rest.split(os.sep): if not part: continue # 遍历当前目录,找到大小写匹配的真实名称 for entry in os.listdir(current_dir): if entry.lower() == part.lower(): current_dir = os.path.join(current_dir, entry) parts.append(entry) break return os.path.join(drive, *parts) # 测试 path = 'c:/users/student/pythonprojects' real_path = get_real_path(path) print(f">>> '{real_path}'")
注意:两种方法都要求目标路径真实存在,如果路径不存在,无法获取到真实的大小写名称。
内容的提问来源于stack exchange,提问作者Wolf
相关产品推荐
相关产品推荐

