Here is a tiny exercise. First, consider the problem of copying the content from one file to another. Let the two files be source.txt and destination.txt (the goal is to copy the content of source.txt into destination.txt). Actually, this can be done in just three lines of Python:
1 2 3
F = open("destination.txt",'w') F.write( open("source.txt").read() ) F.close()
If the file is quite large, then this simple program could fail because the open("source.txt").read() will ask Python to get the entire file content into memory, and there might not be enough memory for that. Instead, here is some code that copies the content of the file one line at a time (supposing it is a file of lines separated by newline characters).
1 2 3 4 5 6
T = open("destination.txt",'w') S = open("source.txt") for line in S: T.write(S) S.close() F.close()
The exercise is this: write code that will copy the lines of source.txt, but change the order, so that target.txt has the lines in reversed order. For instance, if source.txt contains
Take your age add 5 years to it that is your age in five years.
Then after the program runs, target.txt will contain
in five years. that is your age add 5 years to it Take your age