File Handling in Python, Python had a lot of features built in for handling files.
file = open('sample.txt', encoding='utf-8') print(file.read()) # Reads the content of the file
Aroliant is a team on tech, that runs on the Web for the past few years. We are a team of techies indulged in Product Oriented Development, Created super cool products that works across all the industrial leading platforms Android, Chrome and the Web. Our applications are designed with cross-platform compatibility. We have a very strong site ecosystem. We love Open Source and the Web.
Python had a lot of features built in for handling files.
Using the open fuction in Python we can read the files. The open()
function returns a stream object. Here we are going to take a look at the methods and attributes available.
file = open(filename,encoding='utf-8')
Here I have specified the utf-8 encoding, you can use any of the other encodings which are supported by Python.
Attributes
file.name
- returns the file name.
Name is the attribute of the file ,which will return the name of the file that you have opened.
file.encoding
- returns the encoding of the file
file.mode
- returns the mode, read or write.
file.readlines()
- reads all lines of the files
Reading first 5 character
file.read(5)
- returns first 5 characters
Syntax :
file.seek(position)
Example :
file.seek(0)
- seeking to first position.
file.tell()
- tells the current position.
file.close()
- Closes the file stream.
Checking whether the file is closed or not
file.closed
- returns True or False based on the status of the file.
This is the sample file used for this example
sample.txt
Aroliant is a team on tech, that runs on the Web for the past few years.
We are a team of techies indulged in Product Oriented Development, Created super cool products that works across all the industrial leading platforms Android, Chrome and the Web.
Our applications are designed with cross-platform compatibility. We have a very strong site ecosystem. We love Open Source and the Web.
Comments :