Reputation: 279
I am trying to write a python script that moves a file from one directory to another. I've tried two different solutions, both ending in errors.
Number one:
import os
os.rename('C:\users\python\nonpython\adam.spc','C:\users\python\target\adam.spc')
Gives error
Traceback (most recent call last):
File "C:/Users/Python/movefile.py", line 4, in <module>
os.rename('C:\users\python\nonpython\adam.spc','C:\users\python\target\adam.spc')
WindowsError: [Error 123] Felaktig syntax för filnamn, katalognamn eller volymetikett
("Bad syntax for file name, directory name or volume label")
Number two:
import shutil
def move(src, dest):
shutil.move(src, dest)
src='C:\users\python\nonpython\Adam.spc'
dest='C:\users\python\target\Adam.spc'
move(src,dest)
Gives error
Traceback (most recent call last):
File "C:/Users/Python/movefile2.py", line 9, in <module>
move(src,dest)
File "C:/Users/Python/movefile2.py", line 4, in move
shutil.move(src, dest)
File "C:\Python27\lib\shutil.py", line 301, in move
copy2(src, real_dst)
File "C:\Python27\lib\shutil.py", line 130, in copy2
copyfile(src, dst)
File "C:\Python27\lib\shutil.py", line 82, in copyfile
with open(src, 'rb') as fsrc:
IOError: [Errno 22] invalid mode ('rb') or filename: 'C:\\users\\python\nonpython\\Adam.spc'
What should I do to make this work?
Upvotes: 0
Views: 13331
Reputation: 71
You can not move a file to another directory using rename, you can rename a file using move though. Move can replace an existing file (use /y), rename can't.
You can both use slash or backslash, backslash needs to be escaped by using 2 backslashes where you need 1 and 4 backslashes where you need 2.
Your function move needs a return.
Upvotes: 0
Reputation: 20351
3 options to fix this:
'path/to/your/stuff'
r'path\to\your\stuff'
'path\\to\\your\\stuff'
This needs doing because \
is a special character in strings, for indicating special characters like \n
. Therefore that will end badly when you want to work dynamically with paths.
Upvotes: 3
Reputation: 153
Try replacing your backslashes with forward slashes in the Path:
os.rename('C:/users/python/nonpython/adam.spc','C:/users/python/target/adam.spc')
Upvotes: 0
Reputation: 1499
Your directory names should have slashes instead of backslashes.
import os
src = 'C:/users/python/nonpython/Adam.spc'
dest = 'C:/users/python/target/Adam.spc'
os.rename(src, dest)
Upvotes: 0
Reputation: 7380
try using slashes instead of backslashes - replace \
with /
. or use r'C:\users\python\nonpython\adam.spc'
Upvotes: 0