0

I'm trying to move files from one directory to another using Python - spyder. My file extension is *.OD which python does not support or read.

I have tried using the wildcard and leaving out the file extension (which does not work). Another file extension cannot be used for this particular file. Moving python supported extensions such as .txt and .csv works fine.

import shutil
source = '//Original_Filepath/Extract*.od'
target = '//NewFilePath/Extract_*.od'

shutil.copy(source, target)

There are no errors, it just doesn't move/copy the file.

Thanks,

Sebastin Santy
  • 992
  • 1
  • 7
  • 13
  • As in, there's literally a star in the filename? Or were you expecting wildcard behavior? – user2357112 Jul 15 '19 at 04:47
  • 2
    Possible duplicate of [python copy files by wildcards](https://stackoverflow.com/questions/18371768/python-copy-files-by-wildcards) – Xukrao Jul 15 '19 at 04:57

2 Answers2

2

There are a couple of basic mistakes with how you're trying to copy the files. With shutil.copy you should not specify a glob, but instead the exact source and destination.

If instead you want to copy a set of files from one directory to another and (presuming the added underscore isn't a mistake) change the target, then you should try using pathlib in combination with shutil (and re if needed).

pathlib - Object-oriented filesystem paths

Try adapting this:

import pathlib
import shutil
import re

source = pathlib.Path('//Original_Filepath') # pathlib takes care of end slash
source_glob = 'Extract*.od'
target = pathlib.Path('//NewFilePath')
for filename in source.glob(source_glob):
    # filename here is a Path object as well
    glob_match = re.match(r'Extract(.*)\.od', filename.stem).group(1)
    new_filename = "Extract_{}.od".format(glob_match)
    shutil.copy(str(filename), str(target / new_filename)) # `/` will create new Path

If you're not interested in editing the target nor using any other advanced feature that pathlib provides then see Xukrao's comment.

Joseph Glover
  • 330
  • 3
  • 11
0

Thank you all for your help. Much appreciated! :)

I was also able to copy the file with the below as well (a bit simpler). I left out the * and used a date string instead.

import shutil

from datetime import datetime

now = datetime.now()

Org_from=os.path.abspath('//Original FilePath')

New_to=os.path.abspath('//New Path')

shutil.copy(os.path.join(org_from, 'File_' + now.strftime("%Y%m%d") + '.od'), os.path.join(New_to, 'File_' + now.strftime("%Y%m%d") + '.od'))

Cheers, Jen