Adapted and simplified from Franck Albinet's exercises available here. Also presented by NSRC at APRICOT 2018.
...
For further reference on reading and writing files in Python, look at the official documentation here.
But in In essence to handle files in Python, you first need to open a file (even if it does not exist yet)
Code Block | ||||
---|---|---|---|---|
| ||||
python f = open('log/my_first_file.log', 'w') |
the open
function takes as argument: file name 'log/my_first_file.log'
(relative or full path) and mode: read, write, ...
Once open, you get a file object to play with and hence can start writing data in it:
...
Then you need to close the file to free up any system resources taken up by the open file. After calling
Code Block | ||||
---|---|---|---|---|
| ||||
f.close() |
...
attempts to use the file object will automatically fail.
...
Finally, before creating a folder or a file, we would like to test if it exists already. The code below test it and recap. the whole process:{code
Code Block | ||||||
---|---|---|---|---|---|---|
| ||||||
import os file_path = '/flash/log' try: os.listdir('/flash/log') print('/flash/log file already exists.') except OSError: print('/flash/log file does not exist. Creating it ...') os.mkdir('/flash/log') name = '/my_first_file.log' # Writing with open(file_path + name, 'w') as f: f.write('Testing write operations in a file.') # Reading with open(file_path + name, 'r') as f: print(f.readall()) |
...