LinuxQuestions.org
Help answer threads with 0 replies.
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
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.

Notices



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

Rep: Reputation: 0
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?
 
Old 06-24-2009, 07:11 PM   #2
bannock
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:

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

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


Reply

Tags
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 11:50 AM
What is wrong with this python code ? indian Programming 5 09-22-2005 03:20 PM
Trouble Python Code Gerardoj Programming 0 11-30-2003 05:31 PM


All times are GMT -5. The time now is 08:11 PM.

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