为什么os.path.join()在这种情况下不起作用?

本文翻译自:Why doesn't os.path.join() work in this case?

The below code will not join, when debugged the command does not store the whole path but just the last entry. 下面的代码将不会加入,在调试时该命令不会存储整个路径,而只会存储最后一个条目。

os.path.join('/home/build/test/sandboxes/', todaystr, '/new_sandbox/')

When I test this it only stores the /new_sandbox/ part of the code. 当我对此进行测试时,它仅存储代码的/new_sandbox/部分。


#1楼

参考:https://stackoom.com/question/8ADo/为什么os-path-join-在这种情况下不起作用


#2楼

os.path.join()可以与os.path.sep结合使用,以创建绝对路径而不是相对路径。

os.path.join(os.path.sep, 'home','build','test','sandboxes',todaystr,'new_sandbox')

#3楼

The latter strings shouldn't start with a slash. 后面的字符串不应以斜杠开头。 If they start with a slash, then they're considered an "absolute path" and everything before them is discarded. 如果它们以斜杠开头,则它们被认为是“绝对路径”,并且丢弃它们之前的所有内容。

Quoting the Python docs for os.path.join : Python文档引用os.path.join

If a component is an absolute path, all previous components are thrown away and joining continues from the absolute path component. 如果组件是绝对路径,则所有先前的组件都将被丢弃,并且连接将从绝对路径组件继续。

Note on Windows, the behaviour in relation to drive letters, which seems to have changed compared to earlier Python versions: 请注意,在Windows上,与驱动器号有关的行为,与早期的Python版本相比似乎已发生变化:

On Windows, the drive letter is not reset when an absolute path component (eg, r'\\foo' ) is encountered. 在Windows上,遇到绝对路径成分(例如r'\\foo' )时,不会重置驱动器号。 If a component contains a drive letter, all previous components are thrown away and the drive letter is reset. 如果组件包含驱动器号,则会丢弃所有先前的组件,并重置驱动器号。 Note that since there is a current directory for each drive, os.path.join("c:", "foo") represents a path relative to the current directory on drive C: ( c:foo ), not c:\\foo . 请注意,由于每个驱动器都有一个当前目录,所以os.path.join("c:", "foo")代表相对于驱动器C:c:foo )上当前目录的路径,而不是c:\\foo


#4楼

Do not use forward slashes at the beginning of path components, except when refering to the root directory: 除了在引用根目录时,不要在路径组件的开头使用正斜杠:

os.path.join('/home/build/test/sandboxes', todaystr, 'new_sandbox')

see also: http://docs.python.org/library/os.path.html#os.path.join 另请参见: http : //docs.python.org/library/os.path.html#os.path.join


#5楼

仅尝试使用new_sandbox

os.path.join('/home/build/test/sandboxes/', todaystr, 'new_sandbox')

#6楼

It's because your '/new_sandbox/' begins with a / and thus is assumed to be relative to the root directory. 这是因为你的'/new_sandbox/'有开始/因而被认为是相对于根目录。 Remove the leading / . 删除前导/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值