Reputation: 123
I want to iterate through a list in python and printing it with the word 'hello' after it. However, I am not getting the desired output.
The code reads a text file which has numeric ID's. I have created a list of the read ID and used a for loop to iterate through it. Following is my code:
def read_file():
pmid_s = []
file_object = open("file.txt", "r", encoding='cp1252')
pmid =file_object.read()
pmid_s.append(pmid)
for pmid in pmid_s:
return(pmid)
def driver(pmid):
print("hello"+pmid)
def main():
pmid= read_file
driver(pmid)
if __name__ == '__main__':
main()
The desired output is as follows in new line:
hello1
hello2
hello3
hello4
hello5
Upvotes: 0
Views: 91
Reputation: 767
If I understand your question correctly, you need to use driver(pmid) instead of return(pmid). Also you can split what you read directly using the split() method, and there's no need to append after that. See below:
def read_file():
pmid_s = []
file_object = open("file.txt", "r", encoding='cp1252')
pmid_s =file_object.read().split()
for pmid in pmid_s:
driver(pmid)
def driver(pmid):
print("hello {} \n ".format(pmid))
def main():
pmid= read_file()
if __name__ == '__main__':
main()
I'm also assuming that the numbers you read are separated by space
Upvotes: 2
Reputation: 530950
You have a file consisting of a series of integers, one per line. A file iterator yields the lines of the file. You can build the list by iterating over the file itself.
def read_file(fname):
with open(fname, "r", encoding='cp1252') as f:
return [line.strip() for line in f]
def driver(s):
print("hello" + s)
def main():
for num in read_file("file.txt"):
driver(s)
if __name__ == "__main__":
main()
If you want to do it lazily, make read_file
a generator function.
def read_file(fname):
with open(fname, "r", encoding='cp1252') as f:
for line in f:
yield line.strip()
This only ever reads a single line of the file into memory at a time, when a consumer tries to read the next item from the resulting generator.
Upvotes: 1