簡體   English   中英

經過幾次嘗試后,我無法通過shutil.move將文件從一個文件夾移動到另一個文件夾

[英]I cannot move files from one folder to another with shutil.move after several attempts

有許多帖子與將多個文件從一個現有目錄移動到另一個現有目錄有關。 不幸的是,在Windows 8和Python 2.7中,這對我來說還行不通。

我最好的嘗試似乎是與此代碼,因為shutil.copy可以正常工作,但是使用shutil.move可以得到

WindowsError:[錯誤32]該進程無法訪問該文件,因為它正在被另一個進程使用

import shutil
import os

path = "G:\Tables\"
dest = "G:\Tables\Soil"

for file in os.listdir(path):
    fullpath = os.path.join(path, file)
    f = open( fullpath , 'r+')
    dataname = f.name
    print dataname

    shutil.move(fullpath, dest)

del file

我知道問題是我沒有關閉文件,但已經使用del fileclose.file()嘗試了。

我嘗試的另一種方法如下:

import shutil
from os.path import join

source = os.path.join("G:/", "Tables")
dest1 = os.path.join("G:/", "Tables", "Yield")
dest2 = os.path.join("G:/", "Tables", "Soil")

#alternatively
#source = r"G:/Tables/"
#dest1 = r"G:/Tables/Yield"
#dest2 = r"G:/Tables/Soil"

#or
#source = "G:\\Tables\\Millet"
#dest1 = "G:\\Tables\\Millet\\Yield"
#dest2 = "G:\\Tables\\Millet\\Soil"

files = os.listdir(source)

for f in files:
    if (f.endswith("harvest.out")):
        shutil.move(f, dest1)
    elif (f.endswith("sow.out")):
        shutil.move(f, dest2)

如果我使用os.path.join(使用“ G:”或“ G:/”),那么我得到

WindowsError: [Error 3] The system cannot find the path specified:
'G:Tables\\Yield/*.*', 

如果我使用正斜杠( source = r"G:/Tables/" ),那么我得到

IOError: [Errno 2] No such file or directory: 'Pepper_harvest.out'*

我只需要一種將文件從一個文件夾移動到另一個文件夾的方法,僅此而已...

shutil.move可能正在當前工作目錄中查找f ,而不是源目錄。 嘗試指定完整路徑。

for f in files:
    if (f.endswith("harvest.out")):
        shutil.move(os.path.join(source, f), dest1)
    elif (f.endswith("sow.out")):
        shutil.move(os.path.join(source, f), dest2)

這應該起作用; 讓我知道是否:

import os
import shutil

srcdir = r'G:\Tables\\'
destdir = r'G:\Tables\Soil'

for filename in os.listdir(path):
    filepath = os.path.join(path, filename)

    with open(filepath, 'r') as f:
        dataname = f.name

    print dataname

    shutil.move(fullpath, dest)

暫無
暫無

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

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