Python 用字符串将输入变量连接到另一个变量

Python 用字符串将输入变量连接到另一个变量,python,python-3.x,Python,Python 3.x,试图找出是否可以在远程PC上使用os.listdir 我想让用户输入计算机名,然后使用os.listdir列出该电脑上的某个目录 import os def listdirtory(): computername = input("What is the computer name? ") completepath = "\\" + computername + "\C$\\users" os.listdir(completepath) listdirtory()

试图找出是否可以在远程PC上使用
os.listdir

我想让用户输入计算机名,然后使用
os.listdir
列出该电脑上的某个目录

import os

def listdirtory():
    computername = input("What is the computer name? ")
    completepath = "\\" + computername + "\C$\\users"
    os.listdir(completepath)

listdirtory()
我遇到的问题是,我需要取出后面的第二个
\
computername和一个
\
在用户之后,因为其读取路径为双\ 像这样:

FileNotFoundError: [WinError 3] The system cannot find the path specified: '\\\testmachine\\\C$\\\users'

如果需要使用
\\\testmachine\C$\users\

,则应使用另一个反斜杠转义文字反斜杠:

completepath = "\\\\" + computername + "\\C$\\users"
或者改用原始字符串:

completepath = r"\\" + computername + r"\C$\users"

如果您想让它在所有操作系统上运行,应该使用
OS.path.join()
,而不是使用
+
连接。