These slides accompany the book "Developing in 60 Minutes: Linux and Python" by Jedidiah Reeser. Visit JedidiahReeser.com/books for sample files and demo video.
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
Developing in 60 Minutes: Linux and Python slides
1. Developing in 60 Minutes
Linux and PythonLinux and Python
Developing in 60 Minutes
Chapter Six: Tutorial
2. The material in this SlideShare is developed
from the book:
“Developing in 60 Minutes: Linux and Python”
by Jedidiah Reeser
JedidiahReeser.com/books
Also available on Amazon.com
4. To begin, open your text editor and type in the sample file below and
save as “dev_in_60_sample.txt”.
5. Now open up a new file and save it as
“dev_in_60.py”
In your editor, add the following line of code, as
the first line of the “dev_in_60.py”. The first line
is the shebang line and will indicate that the
script should use the Python interpreter for
processing the commands in the file.
#!/usr/bin/env python
6. Now add the code below to open the file so you can
access its contents. In order to open a file, you can
use the “open” method. We pass in the name of the
file, "dev_in_60_sample.txt”, and that we want to
append, “a”, to the file. If you use the “with”
command, it will help ensure that your file safely
closes and frees up system resources.
with open(‘dev_in_60_sample.txt’, 'a') as f:
7. Next, add the text “Hello World!” to the end of the
“dev_in_60_sample.txt” file by indenting with four
spaces and typing the following line:
Notice how the string ends with “n”? That will add a newline character.
f.write('Hello World!n')
8. The script now opens the file and appends a line of text
to the end. To confirm that the code was successfully
implemented, you will need to open the file and print
out the lines onto the screen.
To open the file with read only access, use the with
open command used earlier and change the “a” to a
“r”.
with open(‘dev_in_60_sample.txt’, 'r') as f:
9. To iterate over each line in the file and print it
on the terminal, you can treat the file like a list.
In Python, you can use a for loop to iterate over
the file. It is as simple as:
for line in f:
print line
10.
11. To test the script, run the following command in the directory
where you made the file:
python dev_in_60.py
Your screen output should look like the image below: