gpt4 book ai didi

Python 2.7.10 提示用户输入

转载 作者:太空宇宙 更新时间:2023-11-03 17:32:43 25 4
gpt4 key购买 nike

我正在编写一个 Python 在线教程,并且我正在尝试比它所要求的更进一步的示例问题。

目标是重命名文件夹中的所有文件。我的添加是提示用户输入该文件夹,而不是对其进行硬编码。

我已尝试过 Python: user input and commandline arguments 中的建议,但是当我运行脚本时没有显示提示文本。

就目前情况而言,我的脚本如下所示:

import os
import sys
import optparse
def RName_Files():
#Get the folder to user
Fol = raw_input("Please enter the folder whose files should have numbers stripped from their name: ") #I've never run past this point

#Iterate through the files in the folder
for f in ListDir(f):
print("Current file is '" + f)

我想我误解了我链接的问题的答案,并希望有人能为我澄清答案。特别是因为该线程混合了 2.7 和 3.x。

谢谢!

最佳答案

f当你循环它时,它是未定义的。您是说 ListDir(Fol) ?还有ListDir也是未定义的。

但最重要的是,您没有调用 RName_Files函数在您的程序中,尝试添加 RName_Files()在脚本的末尾。

什么可行

import os

ListDir = os.listdir

def RName_Files():
#Get the folder to user
Fol = raw_input("Please enter the folder whose files should have numbers stripped from their name: ")

#Iterate through the files in the folder
for f in ListDir(Fol):
print("Current file is '" + f)

if __name__ == "__main__":
RName_Files()

您还应该遵循变量和函数名称的 PEP8 命名约定。在Python中,变量和函数是snake_case,而类名是CamelCase。而且你的名字也可以更清晰,rename_files而不是RName_Files , folderpath而不是Fol , file_name而不是f .

看起来像这样:

from os import listdir

def rename_files():
#Get the folder to user
path = raw_input("Please enter the folder whose files should have numbers stripped from their name: ")

#Iterate through the files in the folder
for file_name in listdir(path):
print("Current file is " + file_name )
# do something with file_name

if __name__ == "__main__":
rename_files()

关于Python 2.7.10 提示用户输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31662725/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com