I have an annoying problem in python 2.7 on windows XP. I've got some code that collects a file name off the command line with the argparse library. I then try and open said file. Normally, this works fine, and if you pass in a full path name it successfully opens that too. However, if the path uses a drive letter other than the location you started from, python fails with an IO error, stating that the file or directory does not exist.
For example:
C:\>schema_split.py "C:\path\to\file"
works!
C:\>schema_split.py "I:\path\to\file"
fails!
Relevant code section:
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:
I don't know why python would have problems with alternate drive letters. The only thing I can come up with is that we run it on a shared drive mapped to a local drive. But for all intents and purposes, the program shouldn't "see" the fact that it is operating on a remote drive.
Thoughts?
I think you may want to try two slashes instead of 1. Also I think this SO Question might be helpful to you.
Two slashes like this C:\>schema_split.py "I:\\path\to\file"
Hope this is helpful.
You are assuming python is having problems with drive letters. It isn't. Your problem is something else.
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")
>>>
As you can see opened a file from another drive using backslashes without error.
Use the following script to diagnose your problem:
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
Pass your path to the script and it will test the path and file name you pass to it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With