为什么我不能将我的文本文件移动到Python中的不同文件夹?

时间:2016-11-12 02:14:49

标签: python shell module shutil

我正在使用Python shutil模块将4个txt文件从FolderA移动到FolderB。

当我运行以下代码时,我收到了追溯错误:

shutil.move('C:\Users\Student\Desktop\FolderA.txt', 'C:\Users\Student\Desktop\FolderB')

但是我知道路径确实存在,因为当我尝试这个命令时它工作正常并将整个文件夹A(包括txt文件)移动到FolderB中:

shutil.move('C:\Users\Student\Desktop\FolderA', 'C:\Users\Student\Desktop\FolderB')

任何方式只移动文本文件而不复制它们?我正在使用Python Shell 2.7,以防您想知道。

2 个答案:

答案 0 :(得分:1)

1,正确地转义路径分隔符,使用双反斜杠或在前面添加r''以指示其原始字符串,如下所示

这个命令没有按你的意图行事,它试图将文件调用FolderA.txt移动到FolderB

shutil.move(r'C:\Users\Student\Desktop\FolderA.txt', r'C:\Users\Student\Desktop\FolderB')

下面的代码应该按照您的意图行事。 使用glob模块grep FolderA中的所有txt文件,然后将它们逐个移动到FolderB

import glob
# this will move all txt file from FolderA into FolderB
# but you need to ensure FolderB exists, else it might create a file named FolderB instead
for f in glob.glob(r'C:\Users\Student\Desktop\FolderA\*.txt'):
    shutil.move(f, r'C:\Users\Student\Desktop\FolderB')

答案 1 :(得分:0)

使用Windows路径时需要使用双反斜杠,否则下一个字符将被转义,从而引发IOError: [Errno 2] No such file or directory:...'。即。

shutil.move('C:\\Users\\Student\\Desktop\\FolderA.txt', 'C:\\Users\\Student\\Desktop\\FolderB')