Python 使用操作系统模块将多个本地/脱机文件保存到目标文件夹

Python 使用操作系统模块将多个本地/脱机文件保存到目标文件夹,python,Python,我正在尝试将仅位于源路径中的所有文件移动到目标路径 代码如下: import os target_path = 'C:/Users/Justi/source/repos/GUI Developmentv3/Test 02' + '\\' source_path ='C:/Users/Justi/source/repos/GUI Developmentv3/' + '\\' for path, dir, files in os.walk(source_path): if files:

我正在尝试将仅位于
源路径
中的所有文件移动到
目标路径

代码如下:

import os

target_path = 'C:/Users/Justi/source/repos/GUI Developmentv3/Test 02' + '\\'
source_path ='C:/Users/Justi/source/repos/GUI Developmentv3/' + '\\' 

for path, dir, files in os.walk(source_path):
    if files:
        for file in files:
            if not os.path.isfile(target_path + file):
                os.rename(path + '\\' + file, target_path + file)
但是,这也会将源文件夹的子目录文件夹中的其他文件移动到目标文件夹中


我可以检查一下如何将代码更改为只移动
源路径
的确切目录下的文件,而不影响
源路径
的子字典中的文件吗?提前谢谢。

我认为问题在于的使用,因为它会走遍整棵树。见文件:

通过自顶向下或自底向上遍历目录树来生成目录树中的文件名

您只对特定文件夹的内容感兴趣,因此更适合:

返回一个列表,其中包含路径给定的目录中的条目名称

以下代码将迭代
目录中的文件,并仅将文件移动到
目标
目录中

import os
import shutil

source = "source"
target = "target"

for f in os.listdir(source):
    print(f"Found {f}")
    if os.path.isfile(os.path.join(source, f)):
        print(f"{f} is a file, will move it to target folder")
        shutil.move(os.path.join(source, f), os.path.join(target, f))