如何在此代码中连接列表和字符串?

时间:2014-02-25 20:34:51

标签: python string python-2.7

import os
from subprocess import call

computers = ['\\dc830mjpzplp', '\\dc830mjpzpva']

path1 = "C:\users\public\desktop"

print os.getcwd()

os.chdir("c:\shortcut")

print os.getcwd()

for i in computers:
call(["robocopy", "c:\shortcut", path1])

我正在尝试添加path1,这是robocopy中计算机中字符串的目标路径。我确定这里有多个错误。我试图简单地将文件复制到多个pc。我知道还有其他方法可以做到这一点,但我正在尝试学习python。谢谢。

从原始编辑: 当我选择'y'

时,我的while循环无效
import os
from subprocess import call

computers = []

print "\n***This script will copy files or folders to specified workstations...***" +"\n"


answer = 'y'

while answer == 'y':
    print "Start by adding a computer name: type DC#xxxx" + "\n"
    name = "\\" + raw_input("> ") 
    computers.append(name)
    print "\n***Add Successful***" + "\n"
    print "Here's the list so far: ", computers 

    print "\nDo you need to add more computers?"
    print "Enter 'y' or 'n'"
    answer = raw_input("> ")

    if answer == 'n':
        print "ok" + "\n"
        break

    else:
        print "I don't understand, please check for typos"
        exit(0)



print "Where is the source directory?"
print "Path can be local or network" + "\n"
source = raw_input("> ")

print "Where is the destination path?"

destination = raw_input("> ")

print "Changing source directory from: " , os.getcwd()

print "Changing source directory to: " , source
os.chdir(source)

print os.getcwd()

for n in computers:
    path = n + destination
call(["robocopy", source, path]) 

2 个答案:

答案 0 :(得分:2)

for c in computers:
  path = c + path1
  # now you can use path

另外,我认为path1不应该以{{1​​}}开头。 C:\应该以所有计算机上显示的Windows共享名称开头。

编辑:你必须转义字符串中的反斜杠。 path1a special meaning in Python strings,您必须改为\

答案 1 :(得分:1)

这里有很多问题。

这可能更接近你想要做的事情:

import os
from subprocess import call

computers = ['\\\\dc830mjpzplp', '\\\\dc830mjpzpva']

path1 = "\\c$\\users\\public\\desktop" # This might work if you are admin on the remote machine.
# path1 = "\\public" # Or maybe this?

for i in computers:
    call(["robocopy", "c:\\shortcut", i + path1])

我在这里看到的一些事情应该是我应该做的。首先,您要复制的文件的名称是什么?其次,您可以复制到哪个远程UNC路径?您无法将c:\快捷方式添加到UNC路径。