Read and Write Files
Last updated Aug 13, 2021Python File Read and Write operations
In Python we can easily edit files we can simply do reading and writing on that files and can easily modify them. In file object, you can manipulate file using read() and write() functions
Read(): read method is used to read the string from the file which is open. This method will read all the data from the file and if there is no stopper or count it will read as much as possible. For the reading method, we use the 'r' keyword.
SYNTAX -
fileObject.read([count]) |
Example:-
f = open("code.txt", "r") print(f.read()) |
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer nec odio. Praesent libero. Sed cursus ante dapibus diam. Sed nisi. Nulla quis sem at |
Write(): To manipulate the file, write in the environment and see what happens then as this method will modify the text in your files and will give you a new output when you call the file. You can use the 'w' keyword for writing in your python file.
SYNTAX-
fileObject.write(string) |
Example:-
file = open('code.txt','w') file.write("This is the write command") file.close() |
How to handle position of the file in python?
In python there are two method to handle the file position.
Tell(): tells the current position in the file
seek(): function is used to change the position of the File Handle to a specific position that is given. The from argument specifies the reference position, the values of the form maybe
Syntax:
fileObject.seek(offset[, whence]) |
offset − This is the position of the read/write pointer within the file.
whence − This is optional and defaults to 0 which means absolute file positioning, other values are 1 which means seek relative to the current position and 2 means seek relative to the file's end
0: sets the reference point at the beginning
1: sets the reference point at the current position
2: sets the reference point at the end
Example
f = open("code.txt", "r") f.seek(0) print(f.tell()) print(f.readline()) f.close() |
0 Learn python that's a great language |
Article Contributed By :
|
|
|
|
110 Views |