在python中的单独驱动器上打开文件

时间:2011-05-18 14:05:01

标签: python windows file-io

我在Windows XP上的python 2.7中遇到了烦人的问题。我有一些代码用argparse库从命令行收集文件名。然后我尝试打开文件。通常,这样可以正常工作,如果传入完整路径名,它也会成功打开。但是,如果路径使用的驱动器号不是您开始的位置,则python会因IO错误而失败,并指出该文件或目录不存在。

例如:

C:\>schema_split.py "C:\path\to\file"
works!
C:\>schema_split.py "I:\path\to\file"
fails!

相关代码部分:

parser = argparse.ArgumentParser(description='Process the Accounting file.', version='%(prog)s 1.1')
parser.add_argument('infile', nargs="+", type=str, help='list of input files')
# get the current arguments and put them into a variable
args = parser.parse_args()
for f in args.infile:
    with open(f, "rb") as mycsv:

我不知道为什么python会出现备用驱动器号的问题。我唯一能想到的是我们在映射到本地驱动器的共享驱动器上运行它。但是出于所有意图和目的,程序不应该“看到”它在远程驱动器上运行的事实。

思想?

3 个答案:

答案 0 :(得分:2)

我想你可能想尝试两个斜杠而不是1.我认为this SO Question可能会对你有所帮助。

这样的两个斜杠C:\>schema_split.py "I:\\path\to\file"

希望这有用。

答案 1 :(得分:2)

您可以使用os.path.normpath来规范化路径,也可以检查路径是否有效。

答案 2 :(得分:2)

您认为python存在驱动器号问题。事实并非如此。你的问题是另一回事。

C:\>python
Python 2.6.6 (r266:84297, Aug 24 2010, 18:46:32) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> f = open(r"U:\foo.txt")
>>> 

正如您所看到的那样,使用反斜杠从另一个驱动器中打开了一个没有错误的文件。

使用以下脚本诊断问题:

import os
import sys

path = sys.argv[1]
basepath, fname = os.path.split(path)
print "directory:", basepath
if os.path.exists(basepath):
    print "directory exists"
else:
    print "directory does not exist!"
    sys.exit()

if not fname:
    print "no filename provided!"
    sys.exit()
print "filename:", fname
if os.path.exists(path):
    print "filename exists"
else:
    print "filename not found!"
    print "directory contents:"
    for fn in os.listdir(basepath):
        print fn

将您的路径传递给脚本,它将测试您传递给它的路径和文件名。