Shutil move function gives invalid arguement error PYTHON
문제
I am writing some code that will go through a file, edit it as a temp file, and than copy the temp file over the new file so as to make the edit. However when using the move method from shutil I keep getting this error :
IOError: [Errno 22] Invalid Argument
I've tried using copy, copy2, and copyfile. Here is a copy of the code :
def writePPS(seekValue,newData):
PPSFiles = findPPS("/pps")
for file in PPSFiles:
#create a temp file
holder,temp = mkstemp(".pps")
print holder, temp
pps = open(file,"r+")
newpps = open(temp,"w")
info = pps.readlines()
#parse through the pps file and find seekvalue, replace with newdata
for data in info:
valueBoundry = data.find(":")
if seekValue == data[0:(valueBoundry)]:
print "writing new value"
newValue = data[0:(valueBoundry+1)] + str(newData)
#write to our temp file
newpps.write(newValue)
else: newpps.write(data)
pps.close()
close(holder)
newpps.close()
#remove original file
remove(file)
#move temp file to pps
copy(temp,"/pps/ohm.pps")
해결책
I am not exactly sure why you are getting that error, but to start you could try cleaning up your code a bit and fixing all those import statements. Its hard to see where the functions are coming from and for all you know you could have a namespace collision eventually.
Lets start here with some actually runnable code:
import shutil
import os
import tempfile
def writePPS(seekValue,newData):
PPSFiles = findPPS("/pps")
for file_ in PPSFiles:
#create a temp file
newpps = tempfile.NamedTemporaryFile(suffix=".pps")
print newpps.name
with open(file_,"r+") as pps:
#parse through the pps file and find seekvalue, replace with newdata
for data in pps:
valueBoundry = data.find(":")
if seekValue == data[0:(valueBoundry)]:
print "writing new value"
newValue = data[0:(valueBoundry+1)] + str(newData)
#write to our temp file
newpps.write(newValue)
else:
newpps.write(data)
#move temp file to pps
newpps.flush()
shutil.copy(newpps.name,"/pps/ohm.pps")
You don't need to read all your lines into memory. You can just loop over each line. You also don't need to manage all those open/close file operations. Just use a with
context and also a NamedTemporaryFile which will clean itself up when it is garbage collected.
Important note, that in your example and above, you are overwriting the same destination file each time for every source file. I left it that way for you to address. But if you start here, we can then begin to figure out why you are getting errors.