A file is an external storage on the hard disk from where data can be stored and retrieved. Python supports reading data from files and writing data to the files. In this part we will be dealing with operations like
Learn Python in 16 hrs from experts
Python file operation comprises of three basic steps. They are-
To open file built-in function open() is used. It returns an object of File which is used with other functions.Syntax:
|r||Opens a file for reading|
|rb||Opens a file for reading only in binary format.|
|w||Opens a file for writing only. Overwrites the file if the file exists.|
|wb||Opens a file for writing only in binary format.|
|a||Opens a file for appending. It does not overwrite the file just add the data in the file and if file is not created then it creates new file|
|ab||Opens a file for appending in binary format.|
write() method is used to write a string into the file.
read() method is used to read data from the File.
It is used to close a file. For this purpose, close() function is used.
So, for instance, we need to the file after we are done with our file operations. We do that by following method.
Methods in File Handling
There are different methods are used which are as follows:
import osos.chdir(“new directory path”)
import osprint os.getcwd()
|close()||To close an open file. It has no effect if the file is already closed.|
|flush()||To flush the write buffer of the file stream.|
|read(n)||To read at most n characters form the file. Remember that it reads till end of file if it is negative or None|
To read and return one line from the file.
Remember that it reads at most n bytes, if specified.
To read and return a list of lines from the file.
Remember that it reads at most n bytes/characters if specified.
|seek(offset,from=SEEK_SET)||It changes the file position to offset bytes, in reference to from (start, current, end).|
|tell()||It returns the current file location.|
|writable()||It returns True if the file stream can be written to.|
|write(s)||To write string s to the file and return the number of characters written.|
|writelines(lines)||To write a list of lines to the file.|
That is how we deal with files in Python. Here, we have also discussed different file methods which will be helpful while working on real-world projects. For beginers, a lot of interview questions can be raised on this topic. Prepare yourself for the best via our Python Interview Questions.
So far, we have discussed the basics in our Python online tutorial, which are the building blocks to write a python program.
Now let us go ahead and discuss how to make our program more robust and secure from potential failures.Click on the next tutorial to find more.
Click on the next tutorial to find more or check how to get Python Certification online.Previous Next
Learn SQL in 16 hrs from experts