Solved

how do i convert bash script to python script

Posted on 2014-09-09
3
1,373 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

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Strings in Python are the set of characters that, once defined, cannot be changed by any other method like replace. Even if we use the replace method it still does not modify the original string that we use, but just copies the string and then modif…
Recently, an awarded photographer, Selina De Maeyer (http://www.selinademaeyer.com/), completed a photo shoot of a beautiful event (http://www.sintjacobantwerpen.be/verslag-en-fotoreportage-van-de-sacramentsprocessie-door-antwerpen#thumbnails) in An…
Learn the basics of lists in Python. Lists, as their name suggests, are a means for ordering and storing values. : Lists are declared using brackets; for example: t = [1, 2, 3]: Lists may contain a mix of data types; for example: t = ['string', 1, T…
Learn several ways to interact with files and get file information from the bash shell. ls lists the contents of a directory: Using the -a flag displays hidden files: Using the -l flag formats the output in a long list: The file command gives us mor…

743 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

12 Experts available now in Live!

Get 1:1 Help Now