File handling (1)
File handling (1)
A file is a named location used for storing data. For example, main.py is a file that is always used to store
Python code.
Python provides various functions to perform different file operations, a process known as File Handling.
1. Read ('r'): Opens a file for reading. If the file does not exist, it raises a FileNotFoundError.
2. Write ('w'): Opens a file for writing. If the file exists, it truncates the file (erases its content). If the
file does not exist, it creates a new one.
3. Append ('a'): Opens a file for appending. It does not truncate the file; new data is written at the end.
If the file does not exist, it creates a new one.
4. Read and Write ('r+'): Opens a file for both reading and writing. The file must exist.
5. Write and Read ('w+'): Opens a file for both writing and reading. It truncates the file if it exists; if
not, it creates a new one.
6. Append and Read ('a+'): Opens a file for both appending and reading. It creates a new file if it
does not exist.
7. Binary Modes: You can also open files in binary mode by adding a 'b' to the mode string. For
example:
• Read binary ('rb')
• Write binary ('wb')
• Append binary ('ab')
• Read and write binary ('r+b')
• Write and read binary ('w+b')
• Append and read binary ('a+b')
In the above example, the code file1.read() reads the content of the file and stores it in
the read_content variable.