Reading and writing files in Python
Reading and writing files in Python
In python, two methods deal with the operations related to reading and writing kinds of stuff. Those methods are:
1. read()
2. write()
Method read()
From the words only it is will understand that this method will read the strings from the opened file. This function takes one argument i.e. number of bytes from the file which is opened. Reading operations is done from the initial point of the file, However, if the count is missing then this function starts reading as more as much, until the end of the file.
Example:
# Open a file using given code
or = open("top.txt", "r+")
str = or.read(10);
print ("Read String is : ", str)
# then close opened file
or.close()
Let’s take the example of file top.txt.
Method write():
This method appends the string to the suggested file. It can handle both binaries as well as txt files also. The interesting thing about this method is that it doesn’t add the newline at the end of the String. The parameter of this function will be seen in the file opened.
Example:
# Open a file
using given code
or = open("top.txt", "wb")
or.write( "Python is easy to learn and short languagen")
# then close opened file
or.close()
The above code will create the top.ext file and add the given content on it and then close the file respectively. Here if you will open this file it will have those parameter contents.
File Position in Python:
Here the tell() method will provide you the current position in the file opened.
Whereas the seek() method is used to change the current file position where the offset as arguments are used to move the number of bytes. From arguments will tell the reference point from where the bytes are to be moved on. Here starts and the end is more focused.
Let us take the example of top.txt, below:
Example:
# Below open open a file name top.txt
or = open("top.txt", "r+")
str = or.read(10)
print ("Read String is : ", str)
# Now below check current position
position1 = or.tell()
print ("Current file position : ", position1)
# below reposition pointer at the starting
position1 = or.seek(0, 0);
str = or.read(10)
print ("Again read String is : ", str)
# close the opendd file
or.close()
