Reputation: 3
I am trying to bring in the links from a .txt file and store them in 'link_name'. The problem is when the loop ends, it only stores the last link of the file in 'link_name'. How do I store all the links into the variable while allowing them to be read separately? I was considering a list, but if that's the proper route, I am unsure how to implement it. Thanks for any help you can offer.
fr = open('links.txt', 'r')
for link in fr:
link_name = link
fr.close()
print(link_name)
Upvotes: 0
Views: 43
Reputation: 1
Instead of simply giving you the correct method, I will explain why your code is not running as intended. The problem with the code you have written is that every time you iterate through a line in the file and store it in the variable it is reassigning the variable to the last line it iterates over. As was mentioned above, it would be best to append each line to a list, or use an expression within a list to store each line.
Upvotes: 0
Reputation: 174816
Just append all the links to a list.
link_name = []
fr = open('links.txt', 'r')
for link in fr:
link_name.append(link)
fr.close()
print(link_name)
OR
Through list comprehension,
link_name = [link for link in open('links.txt', 'r')]
print(link_name)
Upvotes: 1
Reputation: 5383
This is one place where readlines()
might actually be useful!
with open('links.txt', 'r') as fr: link_name = fr.readlines()
print link_names
I know! read enough questions, and you might actually find a place where it might be appropriate to use a function that you had thought you would never use. :)
Upvotes: 1
Reputation: 6251
link_names = list()
with open('links.txt', 'r') as fr:
link_names = [link for link in fr]
print(link_names)
Upvotes: 1