2014-09-29 92 views
0

我的目标:在当前工作目录,如果当时一个叫temp文件夹存在删除,然后创建一个新的,其他人只需创建的文件夹temp。然后将当前工作目录中输入的用户filename复制到新创建的temp文件夹中。无效目录名称错误

问题:我越来越WindowsError at line 8(shutil.rmtree(temp_path))说明The directory name is invalid

user_file_name = raw_input('Enter the file name:') 

cwd = os.getcwd() 

temp_path = cwd + r'\temp' 

if os.path.exists(temp_path): 
    shutil.rmtree(temp_path) 
    os.makedirs(temp_path) 
else: 
    os.makedirs(temp_path) 

temp_xml_path = temp_path + "\\" + user_file_name 
xml_path = cwd + "\\" + user_file_name 

shutil.copyfile(xml_path, temp_xml_path) 
+3

在创建路径,请尝试使用'''os.path.join(temp_path,user_file_name)'' '。 – wnnmaw 2014-09-29 13:02:08

+0

同意@wnnmaw使用['os.path.join'](https://docs.python.org/3/library/os.path.html#os.path.join)创建路径比使用更安全试图追加字符串。其他路径操作也是如此,例如获取相对路径,遍历目录等。 – CoryKramer 2014-09-29 13:02:53

+2

更具描述性的标题如何? – AndyG 2014-09-29 13:03:11

回答

4

通过使用os.path.join()来创建路径,可以避免很多潜在的问题。该功能所做的是自动在操作系统之间插入操作系统的路径分隔符。由于Windows上的分隔符是\,因此可以通过使用它而不是手动字符串连接来让您的生活更轻松。

0

问题的反斜杠。试试做

xml_path.encode("string-escape") 

和temp_xml_path在传递给copyfile之前是一样的。

-1

temp_path是只有一个\,但最好是使用os.path.join

temp_path = cwd + r'\\temp' 
+0

''你可以提出一个更好的标题便携式方法的另一个关键点'r'\ temp''''工作得很好 – wnnmaw 2014-09-29 13:14:50

+0

的确我错了r''是一个原始字符串,所以不需要转义它。 – 2014-09-29 13:17:17

相关问题