How to Make a List With Reading a Text File Python in a Function
Table of Contents Hide
- Steps to Read Text File in Python
- Python open up() function
- Methods for Reading file contents
- Python close() part
- Examples for Reading a Text file in Python
- Example 1 – Read the entire text file using the read() office
- Example two – Read the specific length of characters in a text file using the read() function
- Example 3 – Read a single line in a file using the readline() part
- Case 4- Read text file line by line using the readline() function
- Instance 5 – Read all the lines equally a listing in a file using the readlines() function
Python provides congenital-in functions to perform file operations, such equally creating, reading, and writing files. At that place are mainly ii types of files that Python can handle, normal text files and binary files. In this tutorial, nosotros volition take a look at how to read text files in Python.
Steps to Read Text File in Python
In Python, to read a text file, you demand to follow the below steps.
Step 1: The file needs to be opened for reading using the open() method and pass a file path to the office.
Step two: The next step is to read the file, and this can be achieved using several congenital-in methods such as read() , readline() , readlines() .
Step three: Once the read functioning is performed, the text file must be airtight using the close() role.
Now that we have seen the steps to read the file content let's understand each of these methods earlier getting into examples.
Python open() role
The open() function opens the file if possible and returns the corresponding file object.
Syntax – open up(file, mode='r', buffering=-ane, encoding=None, errors=None, newline=None, closefd=Truthful, opener=None)
The open() part has a lot of parameters. Let's accept a look at the necessary params for reading the text file. It opens the file in a specified mode and returns a file object.
Parameters
- file – path like object which represents the file path
- mode (Optional) – The
modeis an optional parameter. It'south a cord that specifies the mode in which you lot desire to open up the file.
| Mode | Description |
|---|---|
'r' | Open a file for read mode (default if fashion is non specified) |
'due west' | Open a file for writing. Python will create a new file if does not exist or truncates a file content if file exists |
'ten' | Open a file for exclusive creation. |
'a' | Open a file for appending the text. Creates a new file if file does not exist. |
't' | Open up a file in text fashion. (default) |
'b' | Open a file in binary mode. |
'+' | Open a file for updating (reading and writing) |
Example
file = open('C:\hello.txt','r') Methods for Reading file contents
There are three ways to read data from a text file.
-
read(): Theread()function returns the read bytes in the grade of string. This method is useful when yous have a pocket-size file, and you desire to read the specified bytes or entire file and shop it into a cord variable. -
readline(): Thereadline()role returns ane line from a text file and retuns in the form of string. -
readlines(): Thereadlines()function reads all the lines from the text file and returns each line equally a string element in a list.
Python close() part
The file will remain open until you shut the file using the shut() role. Information technology is a must and best practice to perform this operation after reading the data from the file as information technology frees up the memory infinite acquired past that file. Otherwise, it may crusade an unhandled exception.
Examples for Reading a Text file in Python
Example ane – Read the entire text file using the read() function
In the below example, we are reading the unabridged text file using the read() method. The file tin be opened in the read way or in a text mode to read the data, and it can exist stored in the string variable.
# Program to read the unabridged file using read() function file = open up("python.txt", "r") content = file.read() print(content) file.close() # Programme to read the entire file (absolute path) using read() function file = open("C:/Projects/Tryouts/python.txt", "r") content = file.read() impress(content) file.close() Output
Beloved User, Welcome to Python Tutorial Have a great learning !!! Cheers Case ii – Read the specific length of characters in a text file using the read() function
In that location are times where yous need to read the specific bytes in a file. In that case, you tin use the read() function past specifying the bytes. The method volition output only the specified bytes of characters in a file, as shown below.
# Program to read the specific length # of characters in a file using read() function file = open("python.txt", "r") content = file.read(20) impress(content) file.shut() Output
Dear User, Welcome Example 3 – Read a unmarried line in a file using the readline() function
If yous desire to read a unmarried line in a file, and so you could achieve this using readline() function. You also utilise this method to recall specific bytes of characters in a line, similar to the read() method.
# Plan to read unmarried line in a file using readline() office file = open("python.txt", "r") content = file.readline() print(content) file.shut() Output
Dear User, Example iv- Read text file line by line using the readline() office
If you desire to traverse the file line by line and output in whatever format, and then y'all could use the while loop with the readline() method as shown below. This is the most effective mode to read the text file line by line in Python.
# Program to read all the lines in a file using readline() part file = open up("python.txt", "r") while True: content=file.readline() if not content: break print(content) file.close() Output
Dear User, Welcome to Python Tutorial Have a great learning !!! Thank you Case 5 – Read all the lines as a list in a file using the readlines() function
The readlines() method volition read all the lines in the file and outputs in a list of strings, as shown below. After y'all can use the list to traverse and extract the specified content from the list.
# Program to read all the lines as a list in a file # using readlines() function file = open("python.txt", "r") content=file.readlines() print(content) file.shut() Output
['Dearest User,\due north', 'Welcome to Python Tutorial\n', 'Accept a great learning !!!\northward', 'Cheers']
Sign Up for Our Newsletters
Source: https://itsmycode.com/python-read-text-file/
0 Response to "How to Make a List With Reading a Text File Python in a Function"
Post a Comment