LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   Python newbie - a better way to write some code. (http://www.linuxquestions.org/questions/programming-9/python-newbie-a-better-way-to-write-some-code-735396/)

Getafix 06-24-2009 07:06 PM

Python newbie - a better way to write some code.
 
Hello,

I have a question regarding "the python way" to do stuff.
The goal is simple.

1) Open a file
2) Parse it's content
3) split it to a list and move forward.


The file is URL list, really straightforward:

www.google.com
www.yahoo.com
www.bbc.com

The code is like this:

ulist = open('url.txt', 'r')
lines = ulist.read()
lines = lines.split('\n')


# for some reason there is a newline as a last item of the list, so i have to
lines = lines.remove('')

How can i do it better?

bannock 06-24-2009 07:11 PM

Well usually you want to do something with each line, like so:

Code:

for line in open('url.txt'):
    something(line)


bgeddy 06-25-2009 10:22 PM

How about a terse version :
Code:

lines=[line.strip() for line in open("url.txt") if line!="\n"]


All times are GMT -5. The time now is 09:59 AM.