【问题标题】:OS Independent File System Access独立于操作系统的文件系统访问
【发布时间】:2013-06-14 23:17:34
【问题描述】:

我目前发现自己不仅要在工作中学习 python,还要使用 Windows 机器进行编码以部署到 Linux 环境。

我希望做的是一项简单的任务。

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

我可以使用以下代码在我的开发机器上运行它: file = open('c:\\www\\' + result + '.txt', 'w') 其中 'result' 是我要创建的文件名,它也可以在 Linux 环境中使用此代码:file = open('www/' + result + '.txt', 'w')

是否有一种快速简便的方法可以更改我的语法以在两种环境中工作?

【问题讨论】:

  • 一般提示:您也可以在 Windows 中使用斜杠而不是反斜杠(当然,在 Python 脚本或 API 调用中,而不是在 shell 中)
  • import platform;platform.uname(); 可以告诉您当前使用的操作系统,您可以相应地切换变量...

标签: python file io directory


【解决方案1】:

您可能会发现os.path 很有用

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

【讨论】:

  • 您是否希望"/www" 确保其位于基本根目录中?否则它将与 cwd 相关?
  • 在 Windows 环境中包含正斜杠是必要的,以便将其放入 c:\ 根目录。
【解决方案2】:

为了操作系统的独立性,您不应手动硬编码或执行任何特定于操作系统的操作,例如路径分隔符等。这不是两种环境的问题,而是所有环境的问题:

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

【讨论】:

    猜你喜欢
    • 2010-09-14
    • 1970-01-01
    • 1970-01-01
    • 2010-12-22
    • 1970-01-01
    • 1970-01-01
    • 2012-06-17
    • 1970-01-01
    • 2013-04-24
    相关资源
    最近更新 更多