I am confused with indexing in python. I am using the following code to read a line from a file and print the first item in the list. I think that every time a line is read the index is set to zero. I am getting an index out of range for the following code. Please explain where I am going wrong.
fname = input("Enter file name: ")
fh = open(fname)
for line in fh:
line = line.strip()
print(line)
b = line.split()
print(b[0])
It can go bad if the string is empty.
In [1]: line = ' '
In [2]: line = line.strip()
In [4]: b = line.split()
In [5]: b
Out[5]: []
In [6]: b[0]
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-6-422167f1cdee> in <module>()
----> 1 b[0]
IndexError: list index out of range
Perhaps update your code as follows:
fname = input("Enter file name: ")
fh = open(fname)
for line in fh:
line = line.strip()
b = line.split()
if b:
print(b[0])
If line
is blank (in other words it consists only of whitespace and a carriage return) then after line.strip()
it will be the null string.
>>> line = ""
>>> line.split()[0]
Traceback (most recent call last):
File "<pyshell#50>", line 1, in <module>
line.split()[0]
IndexError: list index out of range
In other words, when you use split
on the null string, you get an empty list back. So there is no element zero.
As explained previously, if line is blank, you will get an index error.
If you want to read lines, maybe change a little your code to let Python do the job for you
fname = input("Enter file name: ")
with open(fname) as f
lines = f.readlines()
# f will be closed at end of With statement no need to take care
for line in lines:
line = line.strip()
print(line)
# following line may not be used, as line is a String, just access as an array
#b = line.split()
print(line[0])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.