1

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

我只需要一种方法将文件从一个文件夹移动到另一个文件夹,仅此而已......

4

2 回答 2

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)
于 2015-09-01T19:01:37.053 回答
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)
于 2015-09-01T19:01:58.807 回答