windows上的python能否在unix上使用,在Windows中使用Python使用绝对的Unix路径

I'm creating an application that stores blob files into the hard drive, but this script must run in both linux and windows, the issue is that i want to give it an absolute path from the filesystem root and not one relative to the project files, this because im using git and dont want to deal with excluding all these files from syncing.

So i would like to have something like this:

path = '/var/lib/blob_files/'

file = open(path+'myfile.blob', 'w')

and get a file in unix at:

/var/lib/blob_files/myfile.blob

and in windows at:

C:\var\lib\blob_files\myfile.blob

it could also be relative to the user home folder (/home/user in unix and C:/Users/User in windows) but i guess the problem is very similar.

How can i achieve this? is there any library or function that can help me transparently to convert this paths without having to ask in what plataform is the scrip running all the time?

Of my two options, absolute from root or relative from home folder, which one do you recomend to use?

Thanks in advance for any advice on this

解决方案

Use os.path.abspath(), and also os.path.expanduser() for files relative to the user's home directory:

print os.path.abspath("/var/lib/blob_files/myfile.blob")

>>> C:\var\lib\blob_files\myfile.blob

print os.path.abspath(os.path.expanduser("~/blob_files/myfile.blob"))

>>> C:\Users\jerry\blob_files\myfile.blob

These will "do the right thing" for both Windows and POSIX paths.

expanduser() won't change the path if it doesn't have a ~ in it, so you can safely use it with all paths. Thus, you can easily write a wrapper function:

import os

def fixpath(path):

return os.path.abspath(os.path.expanduser(path))

Note that the drive letter used will be the drive specified by the current working directory of the Python process, usually the directory your script is in (if launching from Windows Explorer, and assuming your script doesn't change it). If you want to force it to always be C: you can do something like this:

import os

def fixpath(path):

path = os.path.normpath(os.path.expanduser(path))

if path.startswith("\\"): return "C:" + path

return path

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值