How to move a file?

后端 未结 9 1854
夕颜
夕颜 2020-11-22 01:07

I looked into the Python os interface, but was unable to locate a method to move a file. How would I do the equivalent of $ mv ... in Python?

&g         


        
相关标签:
9条回答
  • 2020-11-22 01:28

    For either the os.rename or shutil.move you will need to import the module. No * character is necessary to get all the files moved.

    We have a folder at /opt/awesome called source with one file named awesome.txt.

    in /opt/awesome
    ○ → ls
    source
    ○ → ls source
    awesome.txt
    
    python 
    >>> source = '/opt/awesome/source'
    >>> destination = '/opt/awesome/destination'
    >>> import os
    >>> os.rename(source, destination)
    >>> os.listdir('/opt/awesome')
    ['destination']
    

    We used os.listdir to see that the folder name in fact changed. Here's the shutil moving the destination back to source.

    >>> import shutil
    >>> shutil.move(destination, source)
    >>> os.listdir('/opt/awesome/source')
    ['awesome.txt']
    

    This time I checked inside the source folder to be sure the awesome.txt file I created exists. It is there :)

    Now we have moved a folder and its files from a source to a destination and back again.

    0 讨论(0)
  • 2020-11-22 01:29

    Based on the answer described here, using subprocess is another option.

    Something like this:

    subprocess.call("mv %s %s" % (source_files, destination_folder), shell=True)
    

    I am curious to know the pro's and con's of this method compared to shutil. Since in my case I am already using subprocess for other reasons and it seems to work I am inclined to stick with it.

    Is it system dependent maybe?

    0 讨论(0)
  • 2020-11-22 01:33

    This is what I'm using at the moment:

    import os, shutil
    path = "/volume1/Users/Transfer/"
    moveto = "/volume1/Users/Drive_Transfer/"
    files = os.listdir(path)
    files.sort()
    for f in files:
        src = path+f
        dst = moveto+f
        shutil.move(src,dst)
    

    Now fully functional. Hope this helps you.

    Edit:

    I've turned this into a function, that accepts a source and destination directory, making the destination folder if it doesn't exist, and moves the files. Also allows for filtering of the src files, for example if you only want to move images, then you use the pattern '*.jpg', by default, it moves everything in the directory

    import os, shutil, pathlib, fnmatch
    
    def move_dir(src: str, dst: str, pattern: str = '*'):
        if not os.path.isdir(dst):
            pathlib.Path(dst).mkdir(parents=True, exist_ok=True)
        for f in fnmatch.filter(os.listdir(src), pattern):
            shutil.move(os.path.join(src, f), os.path.join(dst, f))
    
    0 讨论(0)
提交回复
热议问题