2013-06-18 114 views
2

我目前发现自己不仅需要在工作中学习python,还需要使用Windows机器来执行编码以部署到Linux环境。与操作系统无关的文件系统访问

我想要做的是,希望是一个简单的任务。

在根目录下有一个名为'www'的子目录(在我的Windows机器上,它是c:\ www),如果它不存在,我需要创建一个文件。

我能得到这个使用此代码我的机器上工作: file = open('c:\\www\\' + result + '.txt', 'w'),其中“结果”是我要创建的文件名,它也是用这个代码工作在Linux环境:file = open('www/' + result + '.txt', 'w')

如果有一种快速简便的方法可以改变我的语法以在两种环境中工作?

+0

一般提示:您可以使用斜杠,而不是反斜杠用于Windows,太(在Python脚本或API调用,而不是在外壳的,当然) –

+0

'import platform; platform.uname();'可以告诉你你目前在哪个操作系统,并且可以相应地切换你的变量... –

回答

5

您可能会发现os.path有用

os.path.join('/www', result + '.txt') 
+1

wouldnt你想''/ www“'确保它在基础根目录下?否则会相对于cwd? –

+0

在Windows环境中包含正斜杠对于将其转到c:\ root是必需的。 –

0

对于OS独立性则不应手动硬代码或做任何事情OS具体,如路径分隔符和等。这不是这两个环境的问题,这是所有环境的问题:

import os 
... 
... 
#replace args as appropriate 
#See http://docs.python.org/2/library/os.path.html 
file_name = os.path.join("some_directory", "child of some_dir", "grand_child", "filename") 
try: 
    with open(file_name, 'w') as input: 
     .... #do your work here while the file is open 
     .... 
     pass #just for delimitting puporses 
    #the scope termination of the with will ensure file is closed 
except IOError as ioe: 
    #handle IOError if file couldnt be opened 
    #i.e. print "Couldn't open file: ", str(ioe) 
    pass #for delimitting purposes 

#resume your work