Jessica Tylka
Jessica Tylka

Reputation: 23

Saving Output as List

I have a text file called urldata.txt which I am opening and reading line by line. I wrote a for loop to read it line by line, but I want to save the output I receive as a list. Here is what I have:

textdata = open("urldata.txt","r")
for line in textdata:
    print(line)

this returns:

http://www.google.com

https://twitter.com/search?q=%23ASUcis355

https://github.com/asu-cis-355/course-info

I want to save these lines above as a list. Any suggestions? I have tried appending and such, however, being new to Python I'm not sure how to go about this.

Upvotes: 0

Views: 1436

Answers (2)

ShadowRanger
ShadowRanger

Reputation: 155353

If you just want the lines as a list, that's trivial:

with open("urldata.txt") as textdata:
    lines = list(textdata)

If you want newlines stripped, use a list comprehension to do it:

with open("urldata.txt") as textdata:
    lines = [line.rstrip('\r\n') for line in textdata]

Upvotes: 0

OneCricketeer
OneCricketeer

Reputation: 191701

You just want a list of every line of the file?

urls = open("urldata.txt").read().splitlines() 

Upvotes: 1

Related Questions