Reputation: 11
There are many posts related with moving several files from one existing directory to another existing directory. Unfortunately, that has not worked for me yet, in Windows 8 and Python 2.7.
My best attempt seems to be with this code, because shutil.copy
works fine, but with shutil.move
I get
WindowsError: [Error 32] The process cannot access the file because it is being used by another process
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
I know that the problem is that I don't close the files, but I've already tried it, both with del file
and close.file()
.
Another way I tried is as follows:
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)
If I use os.path.join (either using "G:" or "G:/"), then I get
WindowsError: [Error 3] The system cannot find the path specified:
'G:Tables\\Yield/*.*',
If I use forward slashes (source = r"G:/Tables/"
), then I get
IOError: [Errno 2] No such file or directory: 'Pepper_harvest.out'*
,
I just need one way to move files from one folder to another, that's all...
Upvotes: 1
Views: 3703
Reputation: 12002
This should work; let me know if it doesn't:
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)
Upvotes: 0
Reputation: 76184
shutil.move
is probably looking in the current working directory for f
, rather than the source directory. Try specifying the full path.
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)
Upvotes: 1