如何在没有.py文件位于源位置的情况下使程序移动文件

时间:2016-07-01 13:58:35

标签: python file python-3.x

我编写了这个程序,将视频从我的下载文件夹移动到不同的目标文件夹。

import os
import shutil
import sys
folder = []
highlight = ['highlights','goals','skills']
comedy_word = ['comedy', 'acapella','seyilaw','basketmouth','basket mouth','bovi','gordons','buchi','rhythm unplugged','elenu','seyi law','akpororo','emmaohmygod','klint','shakara','funnybone','igodye','i go die','i go dye','igodye','whalemouth','whale mouth','daniel']
series_word = ['lost', 'thrones', 'vampire', 'originals', 'ship', '']
grub_word = ['programming', 'python', 'linux','exploit','hack']


for i in os.listdir('C:\\Users\\Afro\\Downloads\\Video'):
    folder.append(i.lower())


def tv_series(series):
    for serie in series:
        if 'ship' in serie:
            shutil.move(serie, 'C:\\Users\\Afro\\Desktop\\Movies\\Series\\The Last Ship\\The Last Ship 3\\' )
            print(serie[:-3] +': Moved!')

        elif 'lost' in serie:
            shutil.move(serie, 'C:\\Users\\Afro\\Desktop\\Movies\\Series\\Lost\\s2\\' )
            print(serie[:-3] +': Moved!')

文件的名称是arrange.py,当arrange.py不在" C:\ Users \ Afro \ Downloads \ Video"中时,程序会抛出filenotfound错误。夹。是否可以让程序在任何文件夹中运行? 谢谢 这是它抛出的错误。

Traceback (most recent call last):
File "C:\Users\Afro\AppData\Local\Programs\Python\Python35\lib\shutil.py", line 538, in move
os.rename(src, real_dst)
FileNotFoundError: [WinError 2] The system cannot find the file specified: 'lost - s02e08 (o2tvseries.com).mp4' -> 'C:\\Users\\Afro\\Desktop\\Movies\\Series\\Lost\\s2\\lost - s02e08 (o2tvseries.com).mp4'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "C:\Users\Afro\Desktop\Arrange.py", line 77, in <module>
start(folder)
File "C:\Users\Afro\Desktop\Arrange.py", line 65, in start
tv_series(folder)
File "C:\Users\Afro\Desktop\Arrange.py", line 22, in tv_series
shutil.move(serie, 'C:\\Users\\Afro\\Desktop\\Movies\\Series\\Lost\\s2\\' )
File "C:\Users\Afro\AppData\Local\Programs\Python\Python35\lib\shutil.py", line 552, in move
copy_function(src, real_dst)
File "C:\Users\Afro\AppData\Local\Programs\Python\Python35\lib\shutil.py", line 251, in copy2
copyfile(src, dst, follow_symlinks=follow_symlinks)
File "C:\Users\Afro\AppData\Local\Programs\Python\Python35\lib\shutil.py", line 114, in copyfile
with open(src, 'rb') as fsrc:
FileNotFoundError: [Errno 2] No such file or directory: 'lost - s02e08 (o2tvseries.com).mp4'

1 个答案:

答案 0 :(得分:3)

您呼叫shutil.move错误地指定参考点。在收集文件的循环中,您应该使用os.path.join('C:\\Users\\Afro\\Downloads\\Video', i)并将其放入列表中。否则它是所有相对路径,因此FileNotFound错误。

您也可以更改工作目录。这将使脚本的行为就像它在不同的文件夹中一样。这可能会产生一些意想不到的后果,所以要小心。 Details here.

希望这有帮助!