我正在编写一个更大的脚本,它遍历目录结构以对每个文件执行操作。我无法弄清楚如何在命令行中将目标目录作为参数传递(作为 os.walk 的起点)。任何人都可以就我做错了什么提出建议吗?import osimport sysdef main(): for root, dirs, files in os.walk(sys.argv[1]) for item in files: print(items)if __name__ == '__main__': main(sys.argv[1])
1 回答
慕尼黑8549860
TA贡献1818条经验 获得超11个赞
是的,您对 main 的原始调用使 main 不接受任何参数:
import os
import sys
def main(): # this has 0 arguments, instead you included it inside of the func.
for root, dirs, files in os.walk(sys.argv[1]):
for item in files:
print(items)
if __name__ == '__main__':
main(sys.argv[1]) # likely the source of your error since main() has the argument inside the func.
如果您希望 main 有参数:
def main(args): # any generic argument to be called
for root, dirs, files, in os.walk(args):
for item in files:
print(items)
if __name__ = '__main__':
main(sys.argv[1]) # specific argument called by function
添加回答
举报
0/150
提交
取消