Lession 3
After resuming my study I've learned about File handling (I can recall file handling in C).
File handling Python gives us an easy way to manipulate files. We can divide files in two parts, one is test file which contain simple text, and another one is binary file which contain binary data which is only readable by computer.
File opening The key function for working with files in Python is the open() function. The open() function takes two parameters; filename, and mode. There are four different methods (modes) for opening a file:
"r" - Read - Default value. Opens a file for reading, error if the file does not exist "w" - Write - Opens a file for writing, creates the file if it does not exist "a" - Append - Opens a file for appending, creates the file if it does not exist "x" - Create - Creates the specified file, returns an error if the file exists
Creating a file To create a new empty file:
>>> f = open("file.txt", "x")
To Create a new file if it does not exist:
>>> f = open("file.txt", "w")
Opening a file To open a file we use open() function. It requires two arguments, first the file path or file name, second which mode it should open. If we don't mention any mode then it will open the file as read only.
>>> f = open ("file.txt") >>> f <_io.TextIOWrapper name='file.txt' mode='r' encoding='UTF-8'>
Closing a file After opening a file one should always close the opened file. We use method close() for this.
>>> f = open ("file.txt") >>> f <_io.TextIOWrapper name='file.txt' mode='r' encoding='UTF-8'> >>> f.close()
Reading a file To read the whole file at once use the read() method.
>>> f = open("sample.txt") >>> f.read() 'I am Rayan\nI live in Bangalore\nI am from West Bengal\n'
If we call read() again it will return empty string as it already read the whole file. readline() can help you to read one line each time from the file.
>>> f = open("sample.txt") >>> f.readline() 'I am Rayan\n' >>> f.readline() 'I live in Bangalore\n'
To read all the lines in a list we use readlines() method.
>>> f = open("sample.txt") >>> f.readlines() ['I am Rayan\n', 'I live in Bangalore\n', 'I am from West Bengal\n']
We can loop through the lines in a file object.
>>> f = open("sample.txt") >>> for x in f: ... print(x, end=' ') ... I am Rayan I live in Bangalore I am from West Bengal
Example:
>>> f = open("sample.txt", "w") >>> f.write("I am Rayan\nI live in Bangalore\nI am from West Bengal") >>> f.close() >>> f = open("sample.txt", "r") >>> print(f.read()) I am Rayan I live in Bangalore I am from West Bengal
Using the with statement (which I found so cool) In real life scenarios we should try to use with statement. It will take care of closing the file for us.