LinuxQuestions.org
Social Bookmarking all things Linux and Open Source
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

Tags used in this thread
Popular LQ Tags ,

Reply
 
Thread Tools
Old 06-24-2009, 07:06 PM   #1
Getafix
LQ Newbie
 
Registered: Oct 2004
Location: Israel
Distribution: Debian, CentOS
Posts: 19
Thanked: 0
Python newbie - a better way to write some code.


[Log in to get rid of this advertisement]
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?
Getafix is offline  
Tag This Post ,
Reply With Quote
Old 06-24-2009, 07:11 PM   #2
bannock
LQ Newbie
 
Registered: Jun 2009
Location: Toronto
Distribution: Ubuntu, Fedora
Posts: 24
Thanked: 3
Well usually you want to do something with each line, like so:

Code:
for line in open('url.txt'):
    something(line)
bannock is offline     Reply With Quote
Old 06-25-2009, 10:22 PM   #3
bgeddy
Senior Member
 
Registered: Sep 2006
Location: Liverpool - England
Distribution: slackware 12 and current
Posts: 1,160
Thanked: 112
How about a terse version :
Code:
lines=[line.strip() for line in open("url.txt") if line!="\n"]
bgeddy is offline     Reply With Quote

Reply

Bookmarks


Thread Tools

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 07:18 PM.

Main Menu
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
RSS2  LQ Podcast
RSS2  LQ Radio
Twitter: @linuxquestions
identi.ca: @linuxquestions
Facebook: @linuxquestions
Open Source Consulting | Domain Registration