Printing the output on the terminal
- The print keyword can be used to print any type of objects into the computer terminal screen.
- Note that print adds a newline (\n) character at the end of the line. To avoid this, a comma can be put after the object that you want to print.
Dealing with files
Open and Create file objects
- Open() returns a file object and may take two arguments: open(filename,mode), where mode can be "r" (read), "w" (write), "rw" (both read and write) or "a" (append)
Pay special attention that:
- In modes "w" and "a", if the specified filename does not exist, the open() fuction creates it automatically.
- In mode "w", if an existent file is specified in the filename, the original file is overwritten.
- In mode "a", any data written to the file is automatically added to the end.
Dealing with files
Methods for reading file objects
- File objects can be read using several built-in methods
- Note that all these methods exhaust the file contents, but these can still be assigned to variables and used multiple times
Dealing with files
Methods for reading file objects
- Alternatively, the contents of a file can be read with a for loop in a line-by-line basis.
This is also much faster and memory efficient than assigning the whole content of a file to a variable because only one line is actually stored in memory in each loop iteration
Dealing with files
Writing to files
- To write data on a file, the write() method can be used
- Using this method, you can only write string objects into a file. If you wish to write something other than a string, it needs to be converted to a string first
Closing files
A file is automatically closed when the program ends. However, if you are done with a file, you can close it and free up any system resources with the close() method
←→/
#