我正在开发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。
谢谢!
答案 0 :(得分:1)
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
,folder
或path
代替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()
答案 1 :(得分:0)
你需要调用你的方法
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 os.listdir(fol):
print("Current file is '" + f)
RName_Files()
答案 2 :(得分:0)
" pythonic"这样做的方式是这样的:
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(Fol):
print("Current file is '" + f)
def main():
RName_Files()
if __name__ == "__main__":
main()
基本上,您使用def
定义了您的函数,但从未实际调用它。这是一个很好的做法,有一个主要的功能来调用你创建的那些并以这种方式调用它们。