Download your favorite Linux distribution at LQ ISO.
Go Back > Forums > Non-*NIX Forums > Programming
User Name
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.


  Search this Thread
Old 06-24-2009, 06:06 PM   #1
LQ Newbie
Registered: Oct 2004
Location: Israel
Distribution: Debian, CentOS
Posts: 19

Rep: Reputation: 0
Python newbie - a better way to write some code.


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:

The code is like this:

ulist = open('url.txt', 'r')
lines =
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?
Old 06-24-2009, 06:11 PM   #2
LQ Newbie
Registered: Jun 2009
Location: Toronto
Distribution: Ubuntu, Fedora
Posts: 24

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

for line in open('url.txt'):
Old 06-25-2009, 09:22 PM   #3
Senior Member
Registered: Sep 2006
Location: Liverpool - England
Distribution: slackware64 13.37 and -current, Dragonfly BSD
Posts: 1,810

Rep: Reputation: 231Reputation: 231Reputation: 231
How about a terse version :
lines=[line.strip() for line in open("url.txt") if line!="\n"]


programing, python

Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off

Similar Threads
Thread Thread Starter Forum Replies Last Post
Python Parse Code snowman81 Programming 3 01-24-2009 10:50 AM
What is wrong with this python code ? indian Programming 5 09-22-2005 02:20 PM
Trouble Python Code Gerardoj Programming 0 11-30-2003 04:31 PM > Forums > Non-*NIX Forums > Programming

All times are GMT -5. The time now is 07:13 PM.

Main Menu
Write for LQ is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Facebook: linuxquestions Google+: linuxquestions
Open Source Consulting | Domain Registration