简体   繁体   中英

Is there a way to use the answers entered by the user in python? (using inquirer)

python beginner here. I'm trying to create a script that recursively renames files in a folder according to set rules (no spaces, numbers, no special characters...). For that, I ask the user, by choosing in a list (all using inquirer) how they wants to rename their files. The problem is that I can't use the user's answers with inquirer. Here is the code:

import os
import re
import inquirer

def space():
    for file in os.listdir("."):
        filewspace = file.replace(" ","")
        if(filewspace != file):
            os.rename(file,filewspace)

def numbers():
    for file in os.listdir("."):
        os.rename(file, file.translate(str.maketrans('','','0123456789')))

questions = [
  inquirer.List('choices',
                message="How do you want to format?",
                choices=['Remove spaces', 'Remove numbers',
                'Remove specials',],
            ),
]
answers = inquirer.prompt(questions)

if (answers) == "space":
    space()
elif (answers) == "numbers":
    numbers()
#else:
    #specials()

When I try to print what is inside "answers" after the user choice, I get this back: https://i.stack.imgur.com/UrraB.jpg

I'm stuck at it... Can anyone help, please?

It seems that the variable answers contains a dictionary. So you have to change you if checks at the bottom with:

if answers["choices"] == "Remove spaces":
    space()
elif answers["choices"] == "Remove numbers":
    numbers()
...

That should have the desired functionality.

Should work using the dictionary.

if (answers['choices'] == "Remove spaces"):
    space()
elif (answers['choices'] == "Remove numbers"):
    numbers()
#else:
    #specials()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM