Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.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中的Split方法正在输出索引错误_Python_Python 3.x - Fatal编程技术网

python中的Split方法正在输出索引错误

python中的Split方法正在输出索引错误,python,python-3.x,Python,Python 3.x,这个程序接收一个txt文件并打印出每行的第一个字。它工作得很好,但最后会打印出这个错误 Traceback (most recent call last): File "C:/Users/vipku/PycharmProjects/untitled/test.py", line 7, in <module> print(f.readline().split()[0]) IndexError: list index out of range 在获取第一

这个程序接收一个txt文件并打印出每行的第一个字。它工作得很好,但最后会打印出这个错误

Traceback (most recent call last):
  File "C:/Users/vipku/PycharmProjects/untitled/test.py", line 7, in <module>
    print(f.readline().split()[0])
IndexError: list index out of range

在获取第一个元素之前检查行是否为空:

f=open(“example.txt”、“r”)
行=f.读行()
对于行中的行:
如果line.strip():
打印(line.split()[0])
请注意:

f = open("example.txt", "r")
for line in f:
    for first in line:
实际上是指:

open file "example.txt" for reading
for every line in that file:
    for every character in that line:
因此,这意味着您的
readline
比实际行数多了一倍-因此,您从
readline
中得到空的
str
,正如所说,如果f.readline()返回一个空字符串,则已到达文件结尾,而空行由“\n”表示,该字符串仅包含一个换行符

如果您想处理一行接一行的问题,那么对使用single
就足够了。您应该检查是否有空行(由单个换行符组成的行-使用
。拆分这些行将导致空列表),因此解决方案可能如下所示:

f = open("example.txt", "r")
for line in f:
    words = line.split()
    if words:
        print(words[0])
f.close()

我利用了空列表为False-y和非空列表为True-y的事实,所以只有
单词
至少有1个元素时才会执行打印。请注意,使用后应关闭文件。您可以隐式地执行此操作,也可以将
与open一起使用。。。取而代之的是方法。您可以从中了解后者。

您的一行必须为空。拆分生成一个列表,如果没有任何可开始的内容,则该列表应为空。错误不是来自拆分;它来自[0]
f = open("example.txt", "r")
for line in f:
    words = line.split()
    if words:
        print(words[0])
f.close()