
open can be used to open a file for reading or writing. In the "open" statement, the second parameter can be:
- a = append to the file
- r = read the file
- w = write (overwrite) to the file
If the file does not exist and "a" (append) or "w" (write) are used, the file will be created. If "r" is used or no operand is used, and the file does not exist, "No such file or directory" will probably be returned so you may want to first use touch to create the file if it does not exist.
#!/usr/bin/python3
from pathlib import Path
Path("/tmp/foo.txt").touch()
Here is the minimal boilterplate code without error handling to append "Hello World" to foo.txt using open. In this example, "Hello World" will NOT be displayed as output while the script is running.
#!/usr/bin/python3
file = open("/tmp/foo.txt", "a")
file.write("Hello World\n")
file.close()
Here is a more practical example, with try/except/else error handling.
#!/usr/bin/python
try:
file = open("/tmp/foo.txt", "a")
except Exception as exception:
print(exception)
else:
file.write("Hello World\n")
file.close()
Or, with open can be used, which has it's pros and cons. It's one less line of code, but perhaps a bit trickier at catching exceptions.
#!/usr/bin/python
with open("/tmp/foo.txt", "a") as file:
file.write("Hello World\n")
If the user invoking the Python script does not have permission to write to /tmp/foo.txt, "Permission Denied" should be returned.
Traceback (most recent call last):
File "testing.py", line 7, in <module>
file = open("/tmp/foo.txt", "r")
IOError: [Errno 13] Permission denied: '/tmp/foo.txt'
Or like this, to use both variables and strings.
#!/usr/bin/python
foo = "Hello"
file = open("/tmp/foo.txt", "a")
file.write(foo + " World\n")
file.close()
There are several built in modules that are part of the Python Standard Library included with your Python installation, such as os (Operating System) and re (Regular Expression) and sys (System).
If you do not want to have to include \n (new line) at the end of each write, you can import sys and then use the following markup.
#!/usr/bin/python3
import sys
foo = "Hello"
sys.stdout = open("/tmp/foo.txt", "a")
print(f"{foo} World")
The following can be used if you want the events to be printed as output while the script is running AND also appended to the log file. Additonally, there is no need to include \n (new line) at the end of each print statement.
#!/usr/bin/python
import sys
class Logger(object):
def __init__(self):
self.terminal = sys.stdout
self.log = open("/tmp/foo.txt", "a")
def write(self, message):
self.terminal.write(message)
self.log.write(message)
def flush(self):
pass
sys.stdout = Logger()
foo="World"
print(f"Hello {foo}")
Did you find this article helpful?
If so, consider buying me a coffee over at