多次尝试后,我无法使用shutil.move将文件从一个文件夹移动到另一个文件夹

时间:2015-09-01 18:48:39

标签: python python-2.7 shutil del

有很多帖子涉及将多个文件从一个现有目录移动到另一个现有目录。不幸的是,在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'*

我只需要一种方法将文件从一个文件夹移动到另一个文件夹,这就是所有......

2 个答案:

答案 0 :(得分:1)

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)

答案 1 :(得分:0)

这应该有用;让我知道它是不是:

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)
相关问题