Python Forum
Trying to iterate through a list...
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Trying to iterate through a list...
#1
Hello again,

Wondering why I can't get this to work...

I have a list of numerical values stored in a .txt file lib.txt, like this:

374837, 387473, 384895, 283473
I would like to open this file, and iterate through each item in the list, to be used as an argument in another function.

The end goal is to make a continuous loop that looks at each item in the list; passing each one as an argument to be used by another function.

Here's what I am trying to do:
def iterateList():
    li=open('lib.txt').readlines()
    li=list(li.split(','))
    print(li)
    
I'm running into a few issues:
In python 3.6 I can't do the
li=list(li.split(','))
line (i'm guessing because it's not a string. But when I convert the list to a string, it will then show as a list inside of another list, or a set of lists.

The second problem is that when I do get something working, it usually prints the entire line, not each of the individual comma separated values per line.

Finally, would this be the proper syntax to pass each item in the list off to be used as an argument in another function?

for i in li:
   otherFunction(i)
Any advice or tips are appreciated!
Reply
#2
Here is a simple way to do this
with open('lib.txt') as infile:
    line = next(infile)
li = [int(x) for x in line.split(',')]
for x in li:
    print(x)
Reply
#3
Just what I needed, thank you!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  list of lists iterate only sends the last value batchenr 1 1,891 Sep-24-2019, 07:04 AM
Last Post: Gribouillis
  Iterate through a list of dictionary and append a new value. erina 1 2,095 May-16-2019, 09:55 AM
Last Post: perfringo
  iterate through a list with comparison of expression Alexandro 6 3,408 Jan-31-2019, 05:16 PM
Last Post: Scorpio
  list iterate .. help anna 5 3,513 Mar-19-2018, 11:53 AM
Last Post: anna
  How to iterate through a list and search for a value fad3r 2 2,842 Jan-23-2018, 02:07 AM
Last Post: fad3r
  having dictionary and list to iterate in for loop Annie 5 5,364 Jan-05-2017, 01:05 PM
Last Post: wavic

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020