Python File input/output
- In order to read data from a file on our hard disk or write results to a
file, we need to
openthe file for reading or writing. To open a file for reading, we use the
withconstruct. It introduces a file descriptor which we callpoem. We indicate that we open the file for reading by using the mode'r'poem_file = '/home/bon/tmp/poem.txt' with open(poem_file, 'r') as poem: for line in poem.readlines(): print(line)
Note how
readlinesreads each line including the newline at the end of each line.printthen adds another newline when it prints out the line leading to a double spacing effect. If we prefer single spacing, we can strip off the trailing newline from each line.with open(poem_file, 'r') as poem: for line in poem.readlines(): print(line.rstrip())
We can also print our poem preceded by line numbers.
with open(poem_file, 'r') as poem: for n, line in enumerate(poem.readlines()): print(f'{n+1:>2} {line.rstrip()}')
To write to a file, we also use
with openbut now we use the mode'w'. Try something like this:with open('/tmp/stuff.txt', 'w') as stuff: for n in range(20): stuff.write(f"{n:2}")