簡體   English   中英

shutil.move()和copy()的問題

[英]Problems with shutil.move() and copy()

我在Stackoverflow上閱讀了一些關於shutil.move,復制和重命名的文章。 使用這些引用,我似乎仍然無法在使用Python 2.7的Windows 7 Professional環境下執行此腳本而沒有錯誤。

我在這做錯了什么?

 import shutil

 shutil.move('C:/Data/Download/Somefile.txt.zip','C:/Data/Archive/')

錯誤:

沒有這樣的文件或目錄:C:/Data/Download/Somefile.txt.zip

我試過//,\\和其他沒有結果的路徑。 我在這里錯過了什么?

這是我使用的參考腳本:

import shutil
import os

source = os.listdir("/tmp/")
destination = "/tmp/newfolder/"

for files in source:
    if files.endswith(".txt"):
        shutil.copy(files,destination)

為了更可靠的路徑構建,我強烈推薦os.path.join

from os.path import join
import shutil

source = join('C', 'Data', 'Download', 'Somefile.txt.zip')
destination = join('C', 'Data', 'Archive')
shutil.move(source, destination)

join在不同平台之間相對可移植,您可以繞過與斜杠,反斜杠和轉義相關的所有痛點。 此外,它允許您將路徑視為它們的原樣,而不是使用字符串作為路徑的代理。

您還可以查看此答案 ,了解更多專業人士。

import shutil

 shutil.move(r'C:/Data/Download/Somefile.txt.zip','C:/Data/Archive/')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM