1

I've read a few articles on Stackoverflow about shutil.move, copy and rename. Using those references, I still can't seem to execute this script without errors under a Windows 7 Professional environment using Python 2.7.

What am I doing wrong here?

 import shutil

 shutil.move('C:/Data/Download/Somefile.txt.zip','C:/Data/Archive/')

Error:

No such file or directory: C:/Data/Download/Somefile.txt.zip

I've tried //, \ and other paths with no result. What am I missing here?

Here is the reference script I was using:

import shutil
import os

source = os.listdir("/tmp/")
destination = "/tmp/newfolder/"

for files in source:
    if files.endswith(".txt"):
        shutil.copy(files,destination)
Fastidious
  • 1,249
  • 4
  • 25
  • 43

2 Answers2

4

For more reliable path construction, I highly recommend os.path.join:

from os.path import join
import shutil

source = join('C', 'Data', 'Download', 'Somefile.txt.zip')
destination = join('C', 'Data', 'Archive')
shutil.move(source, destination)

join is relatively portable between different platforms, and you bypass all of the pain points associated with slashes, backslashes, and escapes. Additionally, it lets you treat paths as what they are, instead of using a string as a proxy for a path.

You can also check out this answer for some more pros.

Community
  • 1
  • 1
huu
  • 7,032
  • 2
  • 34
  • 49
0
import shutil

 shutil.move(r'C:/Data/Download/Somefile.txt.zip','C:/Data/Archive/')
Fastidious
  • 1,249
  • 4
  • 25
  • 43