簡體   English   中英

通過 python 將文件從一個目錄傳輸到另一個目錄

[英]Transfering files from one directory to another via python

我正在嘗試將多個文件從一個目錄移動到另一個目錄。 如果文件以sample_list中的值開頭,我嘗試制作的 function 應該移動文件。 我的問題是有多個文件以sample_list中的值開頭,這似乎導致了shutil 的問題。

import shutil
import os

source = './train/'
dest1 = './test/'

files = [
 '195_reg_6762_1540.npz',
 '1369_reg_7652_-2532.npz',
 '195_reg_1947_-484.npz',
 '1336_reg_6209_1217.npz',
 '1198_reg_3784_-934.npz',
 '12_reg_3992_-10.npz',
 '1369_reg_3214_-91.npz']

test_samples = [195, 1493, 409, 339, 12, 1336]

#Move files which begin with values in test_samples  [edited orig post to fix typo]
for f in files:
    for i in test_samples:
        if (f.startswith(str(i))):
            shutil.move(source+f, dest1)

引發錯誤:

  File "/home/usr/anaconda3/lib/python3.7/shutil.py", line 564, in move
    raise Error("Destination path '%s' already exists" % real_dst)

Error: Destination path '/home/usr/Documents/project/data/test/195_reg_1947_-484.npz' already exists

如果要移動的測試樣本中有多個文件具有值,它總是會失敗。 將以test_samples中的值開頭的文件從source目錄移動到target目錄的正確方法是什么。

當您已經成功運行腳本(或其中的一部分)時,就會發生這種情況。 一旦文件存在於目標目錄中,如果您嘗試替換它,shutil 將引發異常。

查看此修改以檢查文件是否已存在於目標目錄中,如果存在,則將其刪除並將其從源目錄中移回(注意該文件必須再次存在於源目錄中)。 [你的意思是復制而不是移動?]

for f in files:
    for i in test_samples:
        if (f.startswith(str(i))):
            if not os.path.exists(dest1+f):
                shutil.move(source+f, dest1)
            else:
                os.remove(dest1+f)
                shutil.move(source+f,dest1)

暫無
暫無

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

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