Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/324.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python TypeError:需要字符串或缓冲区,找到列表_Python_Typeerror - Fatal编程技术网

Python TypeError:需要字符串或缓冲区,找到列表

Python TypeError:需要字符串或缓冲区,找到列表,python,typeerror,Python,Typeerror,我正在努力学习Python,我被困在练习16的额外学分上。我正在尝试读取我使用主练习16创建的文件。我写的代码如下: # pylint: disable-msg=C0103 """ This script reads and prints a file set from the argv """ from sys import argv filename = argv txt = open(filename) print txt.read() 我试图读取的文件是: Derp Derp R

我正在努力学习Python,我被困在练习16的额外学分上。我正在尝试读取我使用主练习16创建的文件。我写的代码如下:

# pylint: disable-msg=C0103
""" This script reads and prints a file set from the argv """
from sys import argv

filename = argv

txt = open(filename)

print txt.read()
我试图读取的文件是:

Derp Derp
Reading this file
Will it work?

我收到错误:TypeError:强制使用Unicode:需要字符串或缓冲区,找到列表,但我不确定我的文件是列表而不是字符串。

argv
是脚本的参数列表。第一个参数是
argv[1]
。试试这个:

from sys import argv

txt = open(argv[1])

print txt.read()


重要提示:几乎总是列表中的第一项是
0
th项,
argv
是一个例外,因为
0
th参数是您的脚本名。

若要调试,请尝试打印
filename
我也遇到了同样的错误,但用此代码解决了它:

from sys import argv

txt = open(argv[1])

print txt.read()

哇,谢谢!通过打印文件名,我发现文件名是一个数组,或者我想Python称之为列表?无论如何,我通过将
filename=argv
更改为
script,filename=argv
完成了argv的解包,一切都很顺利。我很感激你教我做饭,而不仅仅是喂我。这很有意义,我不知道argv是如何工作的,我将
filename=argv
改为
script,filename=argv
。我很欣赏这个答案,只选择dbr作为正确的答案,因为我将能够在调试我提出的未来问题时使用这个答案作为灵感。