Make Python3 Print First Line Only

This is the place for queries that don't fit in any of the other categories.

Make Python3 Print First Line Only

Postby DevynCJohnson » Sat Jun 01, 2013 12:39 pm

How can I make Python3 print the first line of a file or object? I want to emulate
Code: Select all
awk "NR==1"
using Python3 code only.
Ubuntu 13.04 | Python3.3
User avatar
DevynCJohnson
 
Posts: 21
Joined: Sat May 25, 2013 1:53 pm

Re: Make Python3 Print First Line Only

Postby hansn » Sat Jun 01, 2013 1:10 pm

I'm not sure exactly what you're emulating, however to obtain the first line of a file -
Code: Select all
first = open('my_file.txt').readline()
hansn
 
Posts: 87
Joined: Thu Feb 21, 2013 8:46 pm

Re: Make Python3 Print First Line Only

Postby DevynCJohnson » Sat Jun 01, 2013 1:42 pm

Thank you very much, the code does print the first line. I modified the code little because I did not want a newline to print.

Code: Select all
>>> first = open('1.py').readline().strip()
>>> print(first)
#!/usr/bin/python3
>>>


Without my tweak, this is how the output looks:

Code: Select all
>>> first = open('1.py').readline()
>>> print(first)
#!/usr/bin/python3

>>>
Ubuntu 13.04 | Python3.3
User avatar
DevynCJohnson
 
Posts: 21
Joined: Sat May 25, 2013 1:53 pm

Re: Make Python3 Print First Line Only

Postby stranac » Sat Jun 01, 2013 8:04 pm

DevynCJohnson wrote:
Code: Select all
first = open('1.py').readline().strip()

Note that this will also remove any leading(as well as trailing) whitespace as well.

You might want to use the end parameter of the print() function instead:
Code: Select all
print(first, end='')


Also, some of your questions(like this one) seem very basic.
Have you gone through the official tutorial yet? It's a really good introduction to most python features for people with previous programming experience.
Friendship is magic!

R.I.P. Tracy M. You will be missed.
User avatar
stranac
 
Posts: 1144
Joined: Thu Feb 07, 2013 3:42 pm


Return to General Coding Help

Who is online

Users browsing this forum: Bing [Bot] and 5 guests