Reading and writing a file
Here is a mini cheat sheet for reading and writing a text file.
Read a text file line by line and write each line to another file (copy):
f1 = open('./in.txt', 'r') to = open('./out.txt', 'w') for line in f1: to.write(line) f1.close() to.close()
Variations:
text = f.read() # read the entire file line = f.readline() # read one line at a time lineList = f.readlines() # read the entire file as a list of lines
A to Z, then Z to A
Challenge
Write a Python script which prints the alphabet from “a” to “z”. Reverse its source code as explained in the previous post, i.e. reverse the order of lines and reverse the order of characters in each line. This reversed script should now print the alphabet from “z” to “a”!
Demonstration:
$ python fromAtoZ.py a b c d e f g h i j k l m n o p q r s t u v w x y z $ ./reverse-file.py fromAtoZ.py >za.py $ python za.py z y x w v u t s r q p o n m l k j i h g f e d c b a $ ./reverse-file.py za.py >az.py $ python az.py a b c d e f g h i j k l m n o p q r s t u v w x y z $ diff fromAtoZ.py az.py $
You can find the script reverse-file.py
in my previous post. As you can see, applying reverse-file.py
twice, you get back the original file.
Note that this challenge is not specific to Python. It can be solved in C++ too, for instance.
The solution is below, but first try to solve it yourself.
Read more…
Reverse a file
Exercise
Take a text file and reverse it the following ways: (1) reverse characters in each line, and (2) reverse the order of lines too. Let’s see an example:
Input:
#!/usr/bin/env python print "Please, reverse me completely!"
Output:
"!yletelpmoc em esrever ,esaelP" tnirp nohtyp vne/nib/rsu/!#