2016-11-12 72 views
0

我使用Python shutil模塊移動4 TXT從FolderA文件FolderB中。爲什麼我不能動只是我的文本文件,以不同的文件夾在Python?

當我運行下面的代碼,我收到了追溯錯誤:

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。

+0

什麼是追蹤誤差?你爲什麼認爲'FolderA.txt'等於4個文本文件?你可能想看看'fnmatch'或'glob'模塊。 – AChampion

回答

1

1,正確的逃生路徑分隔符,或者使用雙反斜線或在前面加一個r'',以表明其原始字符串像下面

這個命令不是你做何意,但試圖移動文件調用FolderA.txt到FolderB中下面

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

代碼應該做你的原意。 使用水珠模塊到grep在FolderA所有txt文件,然後通過1將它們移動到1 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') 
+0

是否有可能只使用shutil模塊? – YoungCoder

+0

這是我被指示使用的。 – YoungCoder

+1

我不知道如果多數民衆贊成可能,最多可以使用os.listdir()來獲得的,而不是使用水珠模塊的所有文件列表,如果你想移動文件夾中的一切,而不過濾.txt文件,那麼它是可行的單獨shutil – Skycc

0

您需要使用Windows路徑時,否則下一個字符轉義使用雙反斜線,從而提高了IOError: [Errno 2] No such file or directory:...'。即

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

我的注意的是,雙反斜線還是給了我同樣的錯誤。 – YoungCoder

相關問題