File I/O (Input/Output) operations in Python allow us to work with files on our computer system.
Python provides built-in functions and methods to perform file operations.
Python supports the file-handling process. we can easily perform tasks and handle the files, like read from files and write to files in Python. In another programming language, the file-handling process is lengthy and complicated.
The file-handling process plays an important role when we want data to be stored permanently in the file. A file is a named location on a disk to store related information. We can get access to the stored details (non-volatile) after the program is halted.
Open a File
Reading from a File
Writing to a File
Close the File
To open a file, we use the "open()" function.
We need to specify the "file name" and the "mode" in which we can open the file ('r' for reading, 'w' for writing, 'a' for appending, 'r+' for reading and writing).
file = open("sample.txt", "r")
We can use various methods to read from a file, such as read(), readline(), or readlines().
read(): Reads the entire content of the file
readline(): Reads a single line from the file.
readlines(): Reads all lines from the file and returns them as a list
file = open("sample.txt", "r") # Read entire content content = file.read() # Read a single line line = file.readline() # Read all lines lines = file.readlines()
To write to a file, we can use open method and pass the second argument (write as "w" or append as "a") mode and use the write() method to write content in a file
file = open("sample.txt", "w") file.write("Hello, World!")
After we finish working with a file, it's essential to close it using the close() method.
file.close()
The "with" statement ensures that the file is properly closed after its suite finishes, even if an exception is raised during the operation.
Note: It's recommended to use "with" when working with files to ensure they're properly closed.
with open("sample.txt", "r") as file: content = file.read() # File automatically closed after this block
Open file in read mode using open() method and pass second argument as "r" and read() method allows us to read content from a file.
with open("sample.txt", "r") as file: content = file.read() print(content)
Open file in write mode using open() method and pass second argument as "w" and write() method allows us to write content in a file.
with open("sample.txt", "w") as file: file.write("Hello, World!")
Open file in append mode using open() method and pass second argument as "a" and write() method allows us to append content in a file.
with open("sample.txt", "a") as file: file.write("\nThis is a new line appended.")
Make sure to handle exceptions properly, especially when dealing with file I/O operations, to avoid unexpected errors.