开发者

python normalized path gets reset in a for loop

I am trying to get a normalized path on windows. The paths are stored in a list and i a开发者_StackOverflow中文版m looping over those as follows:

>>> lst = ['C:\\', 'C:\\Windows', 'C:\\Program Files']
>>> lst
['C:\\', 'C:\\Windows', 'C:\\Program Files']
>>> for pth in lst:
...    print pth
...
C:\
C:\Windows
C:\Program Files

Notice that it has removed one backslash from the output C:\ should be C:\.

The output doesn't change even when I normalize the path in the loop as below:

>>> import os
>>> for pth in lst:
...     print os.path.normpath(pth)
...
C:\
C:\Windows
C:\Program Files

Can anyone suggest a fix? Thanks

Update

seems like the suggestions about the raw string is a better way to handle this. But how to specify the string as a raw string within a for loop. Example:

for pth in lst:
    raw_str = rpth

Obviously the above doesn't work . How do I achieve this? r'path/to/file' ?


The double slash is simply string escaping - you need to escape slashes in string literals. Printing lst[0] before the loop will print it without the slash. If you want to really include a double slash in your literal, use the raw string syntax:

>>> lst = ['C:\\', 'C:\\Windows', 'C:\\Program Files']
>>> lst[0]
'C:\\'
>>> print lst[0]
C:\
>>> lst2 = [r'C:\\', r'C:\\Windows', r'C:\\Program Files']
>>> lst2[0]
'C:\\\\'
>>> print lst2[0]
C:\\

EDIT: If you want to double the slashes, you can do a simple string replace:

>>> x = 'C:\\Windows'
>>> print x
C:\Windows
>>> x = x.replace('\\', '\\\\')
>>> print x
C:\\Windows


In Python, when you say

>>> s = 'C:\\'

s contains three characters: C, : and \. This can be easily seen by:

>>> len(s)
3

In Python, as in many other languages, a backslash is used to escape certain characters. For example, a newline is \n, a character with value 0 is \x00, etc. A "real" backslash is \\. So, to actually get two backslashes, you need to escape both, giving:

>>> s = 'C:\\\\'

But, Windows is perfectly happy with / as the separator, so you can do:

>>> s = 'C:/'


\\ is an escape sequence which prints \ as the output. If you want to print C:\\, you'll have to use C:\\\\ as the input string(or use raw strings ...). I can't see why you would want that. Although if you particularly want to, there are different options available.


you need \\? you can use print repr(pth)


If possible, try to use os.path.join() for creating your windows path. You don't have to meddle with slashes as much.

eg

from os.path import join
rootdir="C:\\"
path1 = join(rootdir,"windows")
path2 = join(rootdir,"Program Files")
lst = [ rootdir , path1, path2 ]


Use / for sanity on windows (most programs work with both forms of slashes), but failing that, use r'' whenever you are dealing with backslashed path names.

r'C:\My\Windows\Path'

If you really want double backslashes, then that works too:

r'C:\\My\\Escaped\\Path'
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜