Reputation: 213
I have a text file containing:
5
1 2 3 4 5
and I want to read in the contents into a list in python. The issue I'm facing is that i want to ignore the number 5 which is on the first line in the file. The number 5 represents the number of elements below it which is 5. Instead, i want to only append 1,2,3,4,5 into a list.
[1,2,3,4,5]
I tried this:
file = open('text.txt','r')
textfile = file
lst = []
for line in textfile:
line = line.strip().split(',')
line[1] = int(line[1]) #convert 1,2,3,4,5 into integers
lst.append(line[1])
print(lst)
The error I'm getting is "index out of range".
Upvotes: 0
Views: 84
Reputation: 1
The text file:
5
1 2 3 4 5
3 4 5 6 7
the code:
file = open('C:\\Users\\lenovo\\Desktop\\text.txt','r')
for line in file.readlines()[1:3]:
lst=[int(i) for i in line.strip().split()]
print(lst)
output:
[1, 2, 3, 4, 5]
[3, 4, 5, 6, 7]
I'm poor in English,can't explain it with English,hope you could understand(^__^)
Upvotes: 0
Reputation: 12689
You can try this approach :
with open('file','r') as f:
for line_no,line in enumerate(f):
if line_no%2==0:
pass
else:
print([int(int_) for int_ in line if int_.strip()!=''])
output:
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Upvotes: 0
Reputation: 57135
Add the line next(textfile)
just before the loop. It will discard the first line from the file.
Next, you are not converting the line to intereg numbers. You only convert the second element, line[1]
. The right way to convert is:
lst = [int(i) for i in line.split()]
or
lst = list(map(int, line.split()))
To summarize, your "perfect" program looks like this:
with open('text.txt') as infile:
next(infile)
for line in infile:
lst = [int(i) for i in line.split()]
print(lst)
Upvotes: 2
Reputation: 124
Just want to add a minor correction to @DyZ answer as
If I understand correctly, you want list [1,2,3,4,5]
not ['1,2,3,4,5']
with open('text.txt') as infile:
next(infile)
for line in infile:
lst = [int(i) for i in line.split()]
print(lst)
If you use line.split(',')
with int
it will result into ValueError - invalid literal for int()
Upvotes: 0