Linux与Windows路径转换

对于新写的代码,最好不要用下面的方式,而是在配置文件中定义BASE_PATH,路径的连接都使用os.path.join,这样代码自然就是跨平台的,对于遗留代码,可以通过下面的to_os_path快速提供平台兼容性。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import sys
import os
import re

# 将传入的路径根据当前平台做规范化,以便让路径在Windows和Linux上兼容
# 对于共享或挂载路径,需要共享已经按命名规则挂在到/mnt目录下(在Linux上) 或 已经通过net use建立了连接(在Windows上)
# Windows和Linux上共享或挂载点对应规则:
# \\192.168.1.107\e <=> /mnt/107e
# X: <=> /mnt/X
# \\192.168.1.99\database <=> /mnt/99database
# 用法:
# 将 open(r"\\192.168.1.107\e\NAV\abc.txt")
# 改成 open(to_os_path(r"\\192.168.1.107\e\NAV\abc.txt"))
# 即可做到平台兼容
def to_os_path(path):
if sys.platform == 'linux':
return to_linux_path(path)
else:
return to_windows_path(path)


def to_linux_path(path):
m = re.match(r"\\\\\d+\.\d+\.\d+\.(\d+)\\([^\\])", path)
if m: # 形似一个Windows网络共享地址
return '/mnt/' + m.group(1) + m.group(2) + path[m.span()[1] : ].replace('\\', '/')
m = re.match(r"([a-zA-Z]):\\", path)
if m: # 形似一个Windows本地绝对路径
return '/mnt/' + m.group(1) + '/' + path[m.span()[1] : ].replace('\\', '/')

# 已经是一个Linux的据对路径,或者是Windows或Linux的相对路径
return path.replace('\\', '/')


def to_windows_path(path):
m = re.match(r"/mnt/(\d+)([^\\])", path)
if m:
return r"\\192.168.1.{}\{}{}".format(m.group(1), m.group(2), path[m.span()[1] : ].replace('/', '\\'))
m = re.match(r"/mnt/([a-zA-Z])\b", path)
if m:
return m.group(1) + ":" + path[m.span()[1] : ].replace('/', '\\')
return path.replace('/', '\\')