使用 os.walk 传递变量

Using os.walk with passing a variable

我正在尝试通过制作一个小脚本来学习传递变量,以从输入目录路径复制所有文件并将它们复制到另一个文件夹。

我有一个函数可以验证用户提供的输入路径,然后我希望将其作为变量传递给我的 move_files 函数。

这是我正在尝试的代码:

def verification():
    verify_path = input()
    if verify_path[0] == "\"" and verify_path[-1] != '"':
        verify_path = verify_path[1:]
        pass
    elif verify_path[:-1] == "\"" and verify_path[0] != '"':
        verify_path = verify_path[:-1]
        pass
    elif verify_path[0] == '"' and verify_path[-1] == '"':
        verify_path = verify_path[1:-1]
        pass
    else:
        pass
    print ('Your path is: ' + (verify_path) + '\nIs this okay? If so, hit the y key. If this is not okay hit the n key to change to path or x to exit')
    char = bytes.decode(msvcrt.getch(), encoding="utf-8")
    if char.upper() == 'Y':
        pass
    elif char.upper() != 'Y':
        print ("Please copy and paste in a new path")
        verify_path = input()
    elif char.upper() != 'x':
        exit()
    else:
        pass
    return verify_path

def move_files(original_path):
    cwd = os.getcwd()
    for root, dirs, files in os.walk(original_path):
        for file in files:
            try:
                new_path = os.mkdir(os.path.join(cwd,'Copy Folder'))
            except FileExistsError:
                continue
        path_file = os.path.join(root, dirs, file)
        print(path_file)
        shutil.copy2(path_file,new_path)


def main():
    move_files(original_path =verification())

main()

我最初遇到的错误是 'dirs' 是一个未使用的变量,所以我将它包含在我的 path_file 变量中。

然后我遇到了另一个错误‘UnboundLocalError: local variable 'file' referenced before assignment’

I used this answer as a basis 用于复制文件 I followed this guide 传递变量但遇到问题

任何方向都会有帮助!

您正在 path_file = os.path.join(root, dirs, file) 中使用 file 变量 for 循环之外的行使 python 抛出错误 'UnboundLocalError: local variable 'file' referenced before assignment'

此外,您正试图在 for 循环中多次执行 'Copy Folder'。我认为您应该在复制文件之前在 for 循环之外只执行一次。

您的代码更正:

def move_files(original_path):
    cwd = os.getcwd()
    try:
        new_path = os.mkdir(os.path.join(cwd,'Copy Folder'))
    except FileExistsError:
        pass
    for root, dirs, files in os.walk(original_path):
        for file in files:
             path_file = os.path.join(root, file)
             print(path_file)
             shutil.copy2(path_file,new_path)