Working with files and directories
When it comes to files and directories, Python offers plenty of useful tools. In particular, in the following examples, we will leverage the os and shutil modules. As we'll be reading and writing on the disk, I will be using a file, fear.txt, which contains an excerpt from Fear, by Thich Nhat Hanh, as a guinea pig for some of our examples.
Opening files
Opening a file in Python is very simple and intuitive. In fact, we just need to use the open function. Let's see a quick example:
# files/open_try.py
fh = open('fear.txt', 'rt') # r: read, t: text
for line in fh.readlines():
print(line.strip()) # remove whitespace and print
fh.close()The previous code is very simple. We call open, passing the filename, and telling open that we want to read it in text mode. There is no path information before the filename; therefore, open will assume the file is in the same folder the script is run from. This means that if we run this script from outside the files folder...