Introduction to Python file reading using Python
In Python file reading using python, The file is a storing container that can be store related information. Paper document for a computer. Various types of files store different types of information such as for python coding file xyz.py file, for a text file, for graphic file, data file, directory file. They can be store permanently store data(i.e. Hard Disk).
A basic operation in python by the following order while Python file reading using Python:
- Open a file
- Read a file
- Write a file
- Close the file
Welcome to Fireblaze AI School.
Offer the best course for beginners.
Now, you can save this text file as sample.txt.
Open a file
In python already built-in open() function to open a file.
f = open("machine learning/python/sample.txt") # specifying full path x = open("sample.txt") # open file in current directory
Some specific modes in while opening a file. Such as to read r, for write w, and append a to the file.
The default is reading in text mode.
|r||for file reading. (it is the default)|
|w||for file writing.|
|x||for file exclusive creation|
|a||for file appending at the end of the file|
|t||Open in text mode|
|b||Open in binary mode|
Here, some example
x = open("sample.txt") # read mode 'r' (default mode) x = open("sample.txt",'w') # write in text mode x = open("img.sample",'r+b') # read and write in binary mode
Read a file
To read a file in python, we must use ‘r’ mode.
There are number of methods available for the reading purpose. but we can use ‘r’ (read) method to read in the size number of data.
x = open("sample.txt",'r',encoding = 'utf-8') x.read(4) # read the first 4 data 'fireblaze' x.read(4) # read the next 4 data ' AI ' x.tell() # get the current file position 14 print(x.read()) # read the entire file Fireblaze AI School This file belong to data science project You can also read the file using for...loop. for line in x: ... print(line, end = “ ”) ... Fireblaze AI School This file belongs to a data science project
Write a file
For a write a file in python, we need to open it in write ‘w’.
For binary file is used the write() method.
with open("sample.txt",'w',encoding = 'utf-8') as f: f.write("sample file\n") f.write("In that file\n\n")
This program will create a new file named sample.txt in the current directory if it does not exist. If it does exist, it is overwritten.
Close the file
When, your programming task complete you need to properly close the file. Closing a file is done using the close() method available in python.
x = open("sample.txt") # perform file operations f.close()
Above close() function not safe.Some operation with the file, the program exits without closing file. Try below code:
x = open("sample.txt", encoding = 'utf-8') # perform file operations
Now file are properly closeed.