预期的str,bytes或os.PathLike对象,而不是list

时间:2017-11-20 20:36:50

标签: python

我试图编写这个基本的一小段代码,无论我仍然得到这个错误,即使它在我试图阅读的书中所说的内容。能帮我解决一下吗?我试过搜索,没有解释问题。

from sys import argv

script = argv
filename = argv

txt = open(filename)

print(f"Here's your file {filename}:")
print(txt.read())

print("Type the filename again:")
file_again = input("> ")

txt_again = open(file_again)

print(txt_again.read())

我收到此错误:

    Traceback (most recent call last):
  File "C:/Users/Saman/Desktop/Python_Codes/argv.py", line 6, in <module>
    txt = open(filename)
TypeError: expected str, bytes or os.PathLike object, not list

1 个答案:

答案 0 :(得分:3)

基本上,argv会从命令行返回所有list传入的parameters名称program

所以要创建一个更简单的程序(script.py):

from sys import argv

print(argv)

然后从命令行开始运行它:

python script.py param1 param2

然后它将print

["script.py", "param1", "param2"]

因为这些是parameters传递的program,由spaces分隔。

然后应将您的程序修改为:

script, filename = argv

或简单地说:

filename = argv[1]

然后当你运行类似的东西时运行正常:

python script.py file.txt
从命令行