Solved

how do i convert bash script to python script

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

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 29

Expert Comment

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

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
RoboCopy to Changing External Drives 2 60
parse a file and get data out 11 102
UNIX Script. Send email if failure 8 55
simple bash script needed to unpack tar.gz 4 24
Dictionaries contain key:value pairs. Which means a collection of tuples with an attribute name and an assigned value to it. The semicolon present in between each key and values and attribute with values are delimited with a comma.  In python we can…
Utilizing an array to gracefully append to a list of EmailAddresses
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 if, else, and elif statements in Python 2.7. Use "if" statements to test a specified condition.: The structure of an if statement is as follows: (CODE) Use "else" statements to allow the execution of an alternative, if the …

679 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