本文介绍了使用"/"的平台独立路径级联. ,"\"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在python中,我有变量base_dirfilename.我想将它们连接起来以获得fullpath.但是在Windows下,我应该使用\,对于POSIX /.

fullpath = "%s/%s" % ( base_dir, filename ) # for Linux

如何使该平台独立?

解决方案

您要使用.

使用这种方法而不是使用字符串连接等方法的优势在于,它了解各种特定于OS的问题,例如路径分隔符.例子:

import os

Windows 7 下:

base_dir = r'c:\bla\bing'
filename = r'data.txt'

os.path.join(base_dir, filename)
'c:\\bla\\bing\\data.txt'

Linux 下:

base_dir = '/bla/bing'
filename = 'data.txt'

os.path.join(base_dir, filename)
'/bla/bing/data.txt'

操作系统模块包含许多有用的方法,可用于目录,路径操作以及查找特定于操作系统的信息,例如通过 os.sep

In python I have variables base_dir and filename. I would like to concatenate them to obtain fullpath. But under windows I should use \ and for POSIX / .

fullpath = "%s/%s" % ( base_dir, filename ) # for Linux

How can I make this platform independent?

解决方案

You want to use os.path.join() for this.

The strength of using this rather than string concatenation etc is that it is aware of the various OS specific issues, such as path separators. Examples:

import os

Under Windows 7:

base_dir = r'c:\bla\bing'
filename = r'data.txt'

os.path.join(base_dir, filename)
'c:\\bla\\bing\\data.txt'

Under Linux:

base_dir = '/bla/bing'
filename = 'data.txt'

os.path.join(base_dir, filename)
'/bla/bing/data.txt'

The os module contains many useful methods for directory, path manipulation and finding out OS specific information, such as the separator used in paths via os.sep

这篇关于使用"/"的平台独立路径级联. ,"\"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 19:16
查看更多