首页 > 解决方案 > When converting path variable in a list it prints extra symbols \\

问题描述

First in my code I created variable rootdir:

rootdir = r'\\001\Server\Folder1\Folder2\Folder3\Folder4' # shared drive
print(rootdir)

Output:

\\001\Server\Folder1\Folder2\Folder3\Folder4  # looks good

Then I'm creating a list of paths, so I can attach files from that location

files = [rootdir +  '\\' + 'MyFile.xlsx']
print(files)

Output:

['\\\\001\\Server\\Folder1\\Folder2\\Folder3\\Folder4\\MyFile.xlsx'] # has extra \\

I need to use list of paths in a function:

# function sends email
def send_mail(send_from,rcpt,subject,text ,files):
    assert isinstance(send_to, list)
    assert isinstance(cc, list)
    assert isinstance(files, list) # files need to be a list
    msg = MIMEMultipart()

Now the path has extra \\

Why does it happen and how can I get rid of those \\ to get path look like this:

\\001\Server\Folder1\Folder2\Folder3\Folder4\MyFile.xlsx

标签: pythonpython-3.xpythonpath

解决方案


That's do do with how printing a list evaluates. The actual contents of the list is as you want.

In [9]: print(files)
['\\\\001\\Server\\Folder1\\Folder2\\Folder3\\Folder4\\MyFile.xlsx']

In [10]: for file in files:
    ...:     print(file)
    ...:
\\001\Server\Folder1\Folder2\Folder3\Folder4\MyFile.xlsx

推荐阅读