循环在移动文件脚本上不起作用

2024-06-13 20:27:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我对Python非常陌生,我不明白为什么这段代码什么都不做就崩溃了。它基本上是通过消息和延迟等方式将文件从一个文件夹移动到另一个文件夹

import shutil
import os
import time
    
source_dir = 'C:/Users/Kip/Desktop/tarace'
target_dir = 'C:/Users/Kip/Desktop/tamere'
    
file_names = os.listdir(source_dir)

while True:
    for file_name in file_names:
    shutil.move(os.path.join(source_dir, file_name), target_dir)
    print("OK")
    time.sleep(2)

我做错了什么


Tags: nameimport文件夹sourcetargettimenamesos
1条回答
网友
1楼 · 发布于 2024-06-13 20:27:15

这应该是可行的,但不要忘记它将覆盖相同的命名文件,如果您不想这样做,则必须在移动之前进行检查

import shutil
import os
import time
    
source_dir = 'C:/Users/Kip/Desktop/tarace'
target_dir = 'C:/Users/Kip/Desktop/tamere'
    
while True:
    file_names = os.listdir(source_dir)
    if(file_names):
        print("files found moving..")
        for file_name in file_names:
            old_path = os.path.join(source_dir, file_name)
            new_path = os.path.join(target_dir, file_name)
            shutil.move(old_path, new_path)
            print("file {0} -> moved to {1}".format(old_path, new_path))
    time.sleep(2)

相关问题 更多 >