2016-12-01 23 views
0

基本上我想在我的脚本中执行的操作是将一些文件从dest_path复制到source_path。你可以设置它,看看它是如何工作的 -我的Python脚本在复制时忽略文件

但由于某种原因,它复制第一个文件,并告诉我其余的已被复制,这是不正确的。有没有我没有看到或我做错了?即时通讯相当新的Python很抱歉,如果我做了一些显然是错误的,我只是不能看到它... ...

import time, shutil, os, datetime 

source_path = r"C:\SOURCE"        # Your Source path 
dest_path = r"C:\DESTINATION"       # Destination path 
file_ending = '.txt'         # Needed File ending 
files = os.listdir(source_path)       # defines 
date = datetime.datetime.now().strftime('%d.%m.%Y')  # get the current date 

while True: 
    print("Beginning checkup") 
    print("=================") 
    if not os.path.exists(source_path or dest_path): # checks if directory exists 
     print("Destination/Source Path does not exist!") 
    else: 
     print("Destination exists, checking files...") 
     for f in files: 
      if f.endswith(file_ending): 
       new_path = os.path.join(dest_path, date,) 
       src_path = os.path.join(source_path, f) 
       if not os.path.exists(new_path): # create the folders if they dont already exists 
        print("copying " + src_path) 
        os.makedirs(new_path) 
        shutil.copy(src_path, new_path) 
       else: 
        print(src_path + " already copied") 
        # shutil.copy(src_path, new_path) 

    print("=================") 
    print('Checkup done, waiting for next round...') 
    time.sleep(10) # wait a few seconds between looking at the directory 
+3

'如果不是os.path.exists(source_path或dest_path):'没有做你认为它的做法。 '或'不能这样工作。 – user2357112

+1

如果不是'os.path.exists(new_path)',将检查'source_path'中的每个文件,并且只有第一个文件会进入这个块,因为你在第一次通过 – depperm

+0

创建'new_path' new_path = os.path.join(dest_path,date,)实际上是new_path = os.path.join(dest_path,date,f),但是它会为它复制的每个文件创建另一个文件夹。那不是我想要的,所以我删除了f,现在它做到了。我该如何解决这个问题@deppem – diatomym

回答

1

像@ user2357112提到if not os.path.exists(source_path or dest_path)不是做你的想法。更改为

if not os.path.exists(source_path) or not os.path.exists(dest_path): 

,因为它在if通过创建目录new_path第一次这样只会复制一个文件。像这样的东西应该工作:

if f.endswith(file_ending): 
    new_path = os.path.join(dest_path, date,) 
    src_path = os.path.join(source_path, f) 
    if not os.path.exists(new_path): # create the folders if they dont already exists 
     os.makedirs(new_path) 
    if not os.path.exists(os.path.join(new_path,f)): 
     print("copying " + src_path) 
     shutil.copy(src_path, os.path.join(new_path,f)) 
    else: 
     print(src_path + " already copied") 

如果new_path目录不存在,则使该目录(这应该只发生一次,这if可以在循环外移动以及new_path初始化)。在单独的if中检查文件是否存在于该目录内,如果不将该文件复制到该位置,请打印您的消息。

+0

首先,非常感谢。它确实有用,谢谢你,但我没有完全理解你是如何解决它的。你添加了另一个if语句,你能解释给我,所以我知道代码在做什么?我仍然有很多工作要处理这个脚本,所以我想完全理解它在做什么。希望你能理解,并再次感谢。 – diatomym

+0

@diatomym让我知道如果解释是足够的,或者如果你需要更多 – depperm

+0

啊所以你也可以用os.path.join()检查文件,对不对?这就是为什么我发现它令人困惑,但我现在认为它很清楚。 – diatomym