Solved

how do i convert bash script to python script

Posted on 2014-09-09
3
1,487 Views
Last Modified: 2014-09-09
cat testfile | while read line; do echo this is line nr $line ; done

testfile has line data of :
1
2
3
4

Output:

this is line nr 1
this is line nr 2
this is line nr 3
this is line nr 4

I want the python equivalent of this bash script.

Many thanks
0
Comment
Question by:SurferBob1064
  • 2
3 Comments
 
LVL 28

Accepted Solution

by:
pepr earned 500 total points
ID: 40311906
Try the following code (Python 3):
with open('testfile') as f:
    for line in f:
        print('this is line nr ' + line.rstrip())

Open in new window


The for-loop returns the lines including the newline, and the print also adds the newline by default. This is the reason for .rstrip(). The with construct closes the open file automatically.

The sloppy code could be simpler:
for line in open('testfile'):
    print('this is line nr ' + line.rstrip())

Open in new window

However, it is not the recommended way. The open file will be finally closed, but you should not get used to that shortcut.
0
 

Author Closing Comment

by:SurferBob1064
ID: 40311927
The solution works 100% and I appreciate the explanation. Elegantly done.
0
 
LVL 28

Expert Comment

by:pepr
ID: 40312018
You are welcome. And welcome on the Python board ;)
0

Featured Post

Live: Real-Time Solutions, Start Here

Receive instant 1:1 support from technology experts, using our real-time conversation and whiteboard interface. Your first 5 minutes are always free.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Introduction On September 29, 2012, the Python 3.3.0 was released; nothing extremely unexpected,  yet another, better version of Python. But, if you work in Microsoft Windows, you should notice that the Python Launcher for Windows was introduced wi…
Active Directory replication delay is the cause to many problems.  Here is a super easy script to force Active Directory replication to all sites with by using an elevated PowerShell command prompt, and a tool to verify your changes.
Learn the basics of strings in Python: declaration, operations, indices, and slicing. Strings are declared with quotations; for example: s = "string": Strings are immutable.: Strings may be concatenated or multiplied using the addition and multiplic…
Learn the basics of while and for loops in Python.  while loops are used for testing while, or until, a condition is met: The structure of a while loop is as follows:     while <condition>:         do something         repeate: The break statement m…

813 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now