cd-6
cd-6

Reputation: 190

Using os.walk with passing a variable

I am trying to learn passing variables by making a small script to copy all files from an input directory path and copy them to another folder.

I have one function which verifies the input path the user provides and then I want this passed to my move_files function as a variable.

This is the code of what I am trying to attempt:

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()

I was initially encountering an error that 'dirs' was an unused variable so I included it in my path_file variable.

Then I encountered another error 'UnboundLocalError: local variable 'file' referenced before assignment'

I used this answer as a basis for copying the files I followed this guide to pass variables but am having trouble

Any direction would help!

Upvotes: 0

Views: 1288

Answers (1)

Ajay Dabas
Ajay Dabas

Reputation: 1444

You're using file variable in path_file = os.path.join(root, dirs, file) line outside of for loop which makes python throw the error 'UnboundLocalError: local variable 'file' referenced before assignment'

Also, you're trying to make 'Copy Folder' multiple times in for loop. I think you should do it just once outside of the for loop, before copying the files.

Correction in your code:

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)

Upvotes: 1

Related Questions