1

I'm having difficulties parsing filepaths sent as arguments:

If I type:

os.path.normpath('D:\Data2\090925')

I get

'D:\\Data2\x0090925'

Obviously the \0 in the folder name is upsetting the formatting. I can correct it with the following:

os.path.normpath(r'D:\Data2\090925')

which gives

'D:\\Data2\\090925'

My problem is, how do I achieve the same result with sys.argv? Namely:

os.path.normpath(sys.argv[1])

I can't find a way for feeding sys.argv in a raw mode into os.path.normpath() to avoid issues with folders starting with zero!

Also, I'm aware that I could feed the script with python script.py D:/Data2/090925 , and it would work perfectly, but unfortunately the windows system stubbornly supplies me with the '\', not the '/', so I really need to solve this issue instead of avoiding it.

UPDATE1 to complement: if I use the script test.py:

import os, sys 
if __name__ == '__main__': 
    print 'arg 1: ',sys.argv[1] 
    print 'arg 1 (normpath): ',os.path.normpath(sys.argv[1]) 
    print 'os.path.dirname :', os.path.dirname(os.path.normpath(sys.argv[1])) 

I get the following:

C:\Python>python test.py D:\Data2\091002\ 
arg 1: D:\Data2\091002\ 
arg 1 (normpath): D:\Data2\091002 
os.path.dirname : D:\Data2 

i.e.: I've lost 091002...

UPDATE2: as the comments below informed me, the problem is solved for the example I gave when normpath is removed:

import os, sys 
if __name__ == '__main__': 
    print 'arg 1: ',sys.argv[1] 
    print 'os.path.dirname :', os.path.dirname(sys.argv[1])
    print 'os.path.split(sys.argv[1])):', os.path.split(sys.argv[1])

Which gives:

 C:\Python>python test.py D:\Data2\091002\ 
arg 1: D:\Data2\091002\ 
os.path.dirname : D:\Data2\091002
os.path.split : ('D:\\Data2\\090925', '')

And if I use D:\Data2\091002 :

 C:\Python>python test.py D:\Data2\091002
arg 1: D:\Data2\091002 
os.path.dirname : D:\Data2
os.path.split : ('D:\\Data2', '090925')

Which is something I can work with: Thanks!

4

2 回答 2

5

“丢失”路径的最后一部分与在sys.argv.

如果您使用os.path.normpath()then ,这是预期的行为os.path.dirname()

>>> import os
>>> os.path.normpath("c:/foo/bar/")
'c:\\foo\\bar'
>>> os.path.dirname('c:\\foo\\bar')
'c:\\foo'
于 2009-12-06T14:32:51.430 回答
0

这是一段 Python 代码,用于在目录路径的末尾添加反斜杠:

def add_path_slash(s_path):
    if not s_path:
        return s_path
    if 2 == len(s_path) and ':' == s_path[1]:
        return s_path  # it is just a drive letter
    if s_path[-1] in ('/', '\\'):
        return s_path
    return s_path + '\\'
于 2009-12-06T19:42:57.933 回答