File
File is a named location on disk to store related information. It is used to permanently store data in a non-volatile memory(Hard Disk).Since, Random Access Memory(RAM) is a volatile which losses its data when computer is turned off, we use files for future use of the data.
When we want to read from or write to a file we need to open it first. When we are done, it needs to be closed, so that resources that are tied with the file are freed.
Hence in Python, a file operation takes place in the following order ....
1. Open a file
2. Read or Write (perform operations)
3. Close the file
Let us discuss one by one....
1. Open a File
Python has a built-in function open() to open a file.If you want to do some read or write operation on a file then you have to open the file first so to open the file you can use the open() method. This function returns a file object, also called a handle as it is used to read or modify the file accordingly.
Example
f=open("Python.txt") # open file in current Directory
f=open("c:/python33/Python.txt") # Specifying full path
We can specify the mode while opening a file. In mode we specify whether we want to read, write or append to the file.
We also specify if we want to open the file in text mode or binary mode.
The default is reading in text mode. In this mode we get, strings when reading from the file.
On the other hand, binary mode returns bytes and this is the mode to be used when dealing with the non-text files like image or exe files.
There are various modes for opening a file -
Mode Description
'r' To open a file for reading (default mode).
'w' To open a file for writing. Creates a new file, if it does not exist or truncates the file if it exist.
'x' To open a file for exclusive creation. If the file already exists, the operation fails.
't' To open a file in text mode.(default)
'b' To open a file in binary mode.
'+' To open a file fr updating (reading or writing)
Example
# a file named Python, will be opened with the reading mode.
file=open("Python.txt",'r')
# This will print every line one by one in the file.
for each in file:
print(each)
The open command will open the file in read mode and the for loop will print each line present in the file.
Note: One must keep in mind that the mode argument is not mandatory.If not passed,then python will assume it to be "r" by default.
2. Read or Write operations on File
Read files in Python
To read a file in Python, we must open the file in reading mode.There are various methods available for this purpose. We can use the read(size) method to read in size number of data. If size parameter is not specified, it reads and returns up to the end of the file.
Example
f=open("File.txt", "r", encoding="utf-8")
There is more than one way to read a file in python. If you need to extract a string that contains, all characters in the file then you can use file.read().
f.read() # read rest all data till end of the file.
Another way to read a file is to call a certain number of characters. When the interpreter will read the specified numbers of characters of stored data and return it as a string.
f.read(4) # read only first four character
We can read a file line by line using a for loop. This is both efficient and fast.
Example
for line in f:
print(line, end="")
Note : The lines in file itself has a newline character - "/n".
Moreover, the print() end parameter to avoid two newlines when printing.
We can use readline() method to read individual lines of a file. This methods reads a file till the newline, including the newline character.
Suppose file contain that three lines and the file object is f.
This is my first file
This file
Contains three lines
Example
f.readline()
# "This is my first line\n"
f.readline()
# "This file \n"
f.readline()
# "Contains three lines \n"
Lastly the readlines() method returns a list of remaining lines of the entire file. All these reading method return empty values when end of file(EOF) is reached.
Example
>>> f.readlines()
# "This is my first file \n", "This file \n" , "Contain three lines \n"
Note : we can change our current file cursor(position) using the seek() method. Similarly the tell() method returns our file current position (in number of bytes).
Write to file in Python
In order to write into a file in python we need to open it in write 'w', append 'a' pr exclusive creation 'x' mode.
we need to be careful with the 'w' mode as it well overwrite into the file if it already exist. All previous data are erased.
Writing a string or sequence of bytes (for binary files) is done using write() method. This method returns the number of characters written to the file.
Example
with open("File.txt", 'w', encoding="utf-8") as f:
f.write("my first file\n")
f.write("This file\n")
f.write("contains three lines \n")
This program will create a new file named "File.txt" if it does not exist. If it exist, it is overwritten.we must include the newline characters ourselves to distinguish different lines.
3. Close the File
When we are done with operations to the file, we need to properly close the file.. Closing a file will free up the resources that were tied with the file and is done in python using the close() method.
Python has a garbage collector to clean up referenced objects but, we must not rely on it to close the file.
Example
f=open("File.txt", encoding="utf-8")
#perform file operations
f.close()
This method is not entirely safe. If an exception occurs when we are performing some operation with the file, the code exits without closing the file.
A safer way is to use a try -------- finally block. (We will discuss in Exception Handling)
Example
try:
f=open("File.txt", encoding="utf-8")
# Perform file operations
finally:
f.close()
This way, we are guaranteed that file is properly closed even if any exception is raised,causing program flow to stop.
Note : The best way to do this is using the with statement. This ensures that the file is closed when the block inside with has executed.
We don not need to explicitly call the close() method. It is done internally.
Example
with open("File.txt", encoding="utf-8") as f:
# Perform operations on file.
No comments:
Post a Comment