Reputation: 644
I'm trying to import a comma separated list from a .txt file (lib.txt) into a python list. I would then like to iterate over each item in the list, passing each value as an argument to another function. Once finished, the loop should then continue onto the next item in the list, and be endless in that once it reaches the end of the list, it starts over.
Example of the txt file (lib.txt):
483749, 9384723, 38485903, 4875659, 27388495
Here's what I'm trying:
def iterateList():
li=open('lib.txt').readlines()
li=list(li.split(','))
for i in li:
otherFunction(i)
I'm having a few issues with this code. In python 3.6 I'm unable to run the 3rd line (with li.split), I'm guessing because li is not a string. But if I convert li to a string before trying to split, it also does not work.
Am I approaching this correctly? Would you do it any differently?
Thank you for looking.
Upvotes: 2
Views: 1639
Reputation: 8025
with open("test.txt") as f:
file = f.readlines()
for line in file:
numbers = line.split(", ")
for number in numbers:
number = number.replace("\n", "")
print(number)
outputs:
483749
9384723
38485903
4875659
27388495
with open()
.This ensures that your file operation is being closed by Python after being used. See docs for more information:
It is good practice to use the
with
keyword when dealing with file objects. The advantage is that the file is properly closed after its suite finishes, even if an exception is raised at some point.
.split(", ")
as opposed to .split(",")
Since technically every number is separated by a comma-space, it's easier to take care of both in one go, otherwise you will end up with an output as so:
483749
9384723
38485903
4875659
27388495\n # We remove the '\n' in number 4 below.
This is where the for line in file:
comes in play. After you get the line do you get the numbers; for number in line.split(", ")
.
"\n"
with ""
.Since the end of the line you will have a \n
, make sure to replace it with nothing.
Upvotes: 2
Reputation: 1572
You need to iterate through li
in your code. Check this out as an example:
def iterateList():
li=open('lib.txt').readlines()
for line in li:
items = line.split(',')
for item in items:
print(item)
# otherFunction(item)
Upvotes: 1
Reputation: 5961
readlines
returns a list, and you want to perform split on a string, so you need to use read
instead to return a string.
A possible solution would be:
def iterateList():
with open('lib.txt') as f:
data = f.read().split(',')
while True:
for i in data:
otherFunction(i)
Upvotes: 2