在Python中打开不同驱动器上的文件

3 投票
3 回答
26934 浏览
提问于 2025-04-16 17:53

我在Windows XP上用Python 2.7遇到了一个烦人的问题。我有段代码是用argparse库从命令行获取文件名的。然后我尝试打开这个文件。通常情况下,这个操作没问题,如果你输入的是完整的路径,它也能顺利打开。但是,如果路径使用的是不同于你开始时所在位置的驱动器字母,Python就会报错,提示说文件或目录不存在。

举个例子:

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 个回答

3

你可以使用 os.path.normpath 这个工具来整理文件路径,顺便检查一下这个路径是否有效。

4

我觉得你可以试试用两个斜杠,而不是一个。还有,我觉得这个问题可能对你有帮助。

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

希望这些对你有帮助。

3

你认为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

把你的路径传给这个脚本,它会测试你传入的路径和文件名。

撰写回答