Read all line in file python

Read a file line by line in Python (5 Ways)

In this article we will discuss different ways to read a file line by line in Python.

Suppose we have a file data.txt in same directory as our python script. Let’s see how to read it’s contents line by line.

Solution for Small Files : Get list of all lines in file using readlines()

First basic and inefficient solution is using function readlines().

If we have a small file, then we can call readlines() on the file handler, it reads the whole file content to memory, then splits it into seperate lines and returns a list of all lines in the file. All the lines in list except the last one, will contain new line character in end.
For example,

# Open file fileHandler = open ("data.txt", "r") # Get list of all lines in file listOfLines = fileHandler.readlines() # Close file fileHandler.close() # Iterate over the lines for line in listOfLines: print(line.strip())

Frequently Asked:

sample message string. It is a text file. It contains three lines.

The readlines() function returns a list of lines in file. We can iterate over that list and strip() the new line character then print the line.

But if file size is large then it will consume a lot of memory, so better avoid this solution in case of large files.

Let’s look at some efficient solutions,

Read a file line by line using readline()

While Reading a large file, efficient way is to read file line by line instead of fetching all data in one go.
Let’s use readline() function with file handler i.e.

lineStr = fileHandler.readline()

readline() returns the next line in file which will contain the newline character in end. Also, if end of file is reached then it will return an empty string.
Now let’s see how to read contents of a file line by line using readline() i.e.

# Open file fileHandler = open ("data.txt", "r") while True: # Get next line from file line = fileHandler.readline() # If line is empty then end of file reached if not line : break; print(line.strip()) # Close Close fileHandler.close()
sample message string. It is a text file. It contains three lines.

Read file line by line with context manager (with block)

When we open the file then we need to close that too. If we forget to close then it will be closed automatically when last reference to file handler is destroyed for example at the end of function. But what if we have a large function that is not going to end soon, even if file related work is complete. In that case we can use context manager to automatically cleanup the things like file closure etc.
For example,

# Open file with open ("data.txt", "r") as fileHandler: # Read each line in loop for line in fileHandler: # As each line (except last one) will contain new line character, so strip that print(line.strip())
sample message string. It is a text file. It contains three lines.

In this case when control comes out of with block then file will be automatically closed. Even if it came out of block due to some exception.

Читайте также:  Php проверка доменного имени

Get List of lines in file with context manager (with block)

Let’s Iterate over all the lines in file and create a list of lines i.e.

# Get the all the lines in file in a list listOfLines = list() with open ("data.txt", "r") as myfile: for line in myfile: listOfLines.append(line.strip()) print(listOfLines)

Contents of the list listOfLines will be,

['sample message string.', 'It is a text file.', 'It contains three lines.']

Read contents of file line by line using with context manager and while loop

Let’s iterate over the lines in file with context manager and while loop i.e.

# Open file with open("data.txt", "r") as fileHandler: # Read next line line = fileHandler.readline() # check line is not empty while line: print(line.strip()) line = fileHandler.readline()

Contents of the list will be,

sample message string. It is a text file. It contains three lines.

Complete example to read a file line by lines is as follows

print("****Read all lines in file using readlines() *****") # Open file fileHandler = open ("data.txt", "r") # Get list of all lines in file listOfLines = fileHandler.readlines() # Close file fileHandler.close() # Iterate over the lines for line in listOfLines: print(line.strip()) print("****Read file line by line and then close it manualy *****") # Open file fileHandler = open ("data.txt", "r") while True: # Get next line from file line = fileHandler.readline() # If line is empty then end of file reached if not line : break; print(line.strip()) # Close Close fileHandler.close() print("****Read file line by line using with open() *****") # Open file with open ("data.txt", "r") as fileHandler: # Read each line in loop for line in fileHandler: # As each line (except last one) will contain new line character, so strip that print(line.strip()) print("****Read file line by line using with open *****") # Get the all the lines in file in a list listOfLines = list() with open ("data.txt", "r") as myfile: for line in myfile: listOfLines.append(line.strip()) print(listOfLines) print("****Read file line by line using with open() and while loop *****") # Open file with open("data.txt", "r") as fileHandler: # Read next line line = fileHandler.readline() # check line is not empty while line: print(line.strip()) line = fileHandler.readline()
****Read all lines in file using readlines() ***** sample message string. It is a text file. It contains three lines. ****Read file line by line and then close it manualy ***** sample message string. It is a text file. It contains three lines. ****Read file line by line using with open() ***** sample message string. It is a text file. It contains three lines. ****Read file line by line using with open ***** ['sample message string.', 'It is a text file.', 'It contains three lines.'] ****Read file line by line using with open() and while loop ***** sample message string. It is a text file. It contains three lines.

Источник

Читайте также:  User Form

How to Read a File Line by Line in Python

Dionysia Lemonaki

Dionysia Lemonaki

How to Read a File Line by Line in Python

When coding in Python, there may be times when you need to open and read the contents of a text file.

Luckily enough, there are several ways to do this in Python.

The language has many built-in functions, methods, and keywords that you can use to create, write, read and delete text files.

In this article, you’ll learn the most common ways of reading a file. With the help of coding examples, you will know how to read a text file line by line.

Here is what we will cover:

How to Open a Text File Using the open() Function in Python

Before you start reading a text file in Python, you first need to open it.

To open a text file, use the built-in open() function.

The general syntax for the open() function looks like this:

The open() function accepts multiple arguments, but in this example, I’m focusing only on two: filename and mode .

Let’s break down the syntax.

The first required argument that the open() function accepts is filename , which represents the full path of the file name you want to open.

When specifying the path of the file you want to open, you need to be aware of where that file is located in your folder structure.

For example, if the text file you want to open and your current file with Python code are in the same folder, you only need to reference its name and extension.

Say you have a folder with the name projects .

Inside it, you have two files, main.py , which is the file where you write your Python code, and example.txt , which is the file you would like to open. That file contains the following contents:

I absolutely love coding! I am learning to code for free with freeCodeCamp! 

Both files are on the same level in the folder, so here is how you would reference example.txt when using the open() function:

The second optional argument that the open() function accepts is mode . It specifies whether you want to read ( «r» ), write ( «w» ), or append ( «a» ) to filename .

The default mode is the read ( «r» ) mode.

So, to open and read example.txt , you could optionally use «r» to represent the mode you want to use:

With that said, you don’t need to write the keyword mode .

Instead, you can omit it and only use the letter «r» — it would still have the same result:

Lastly, you can omit the letter «r» altogether as it is the default mode:

When you run the code from the example above, it doesn’t do anything.

You completed the first step, which is opening the text file, but you haven’t read it and seen its contents.

How to Read a Text File Using the read() Method in Python

To read the contents of example.txt , let’s first store the code we wrote in the previous section in a variable named file :

Then, let’s call the read() method on file and print the result to the console:

file = open("example.txt") print(file.read()) # output # I absolutely love coding! # I am learning to code for free with freeCodeCamp! 

Now, you can read the contents of example.txt !

Читайте также:  Docker nginx php fpm postgresql

The read() method reads all the contents as a single string, which is useful when working with smaller files that don’t have a lot of content in the text file.

With that said, the code above is missing something.

Once you have finished reading the text file, you need to close it. To do that, use the close() method. Make sure not to skip this step because forgetting to close the file may introduce bugs in your code!

file = open("example.txt") print(file.read()) # close file file.close() 

Now, closing the text file is a good practice, but it is something that you can easily forget to do — you may not always remember to call the close() method on the file.

There is an alternative available.

The with keyword ensures that the file is automatically closed upon code execution.

The general syntax for the with keyword when used with the open() function is the following:

with open("filename") as variable: # do something with variable 

So, here is how you would rewrite the code from the previous example using the with keyword instead of the close() method:

with open("example.txt") as file: print(file.read()) # output # I absolutely love coding! # I am learning to code for free with freeCodeCamp! 

How to Read a Text File Using the readline() Method in Python

If you want to read only one single individual line from a text file, use the readline() method:

with open("example.txt") as file: print(file.readline()) # output # I absolutely love coding! 

The text file example.txt has two lines inside it, but the readline() method only reads one line from the file and returns it.

The readline() method also adds a trailing newline character at the end of the string.

You can optionally pass a size argument to the readline() method, which specifies the length of the returned line and the maximum number of bytes it will read.

with open("example.txt") as file: print(file.readline(10)) # output # I absolute 

How to Read a Text File Using the readlines() Method in Python

The readlines() method reads all the lines from a file, going through the file line by line.

It then returns a list of strings:

with open("example.txt") as file: print(file.readlines()) # output # ['I absolutely love coding!\n', 'I am learning to code for free with freeCodeCamp!'] 

The readlines() method read all the lines in one go and stored each line from the text file as a single list item inside a list. The readlines() method also added a newline character \n at the end of each line.

How to Read a Text File Using a for Loop in Python

An alternative way of reading a file line by line in Python is using a for loop, which is the most Pythonic approach to reading a file:

with open("example.txt") as file: for item in file: print(item) # output # I absolutely love coding! # I am learning to code for free with freeCodeCamp! 

The open() function returns an iterable object.

The for loop gets paired with the in keyword — they iterate over the returned iterable file object and read each line inside it.

Conclusion

Hopefully, this article helped you understand how to read a file line by line in Python using the read() , readline() , and readlines() methods and a for loop.

Thank you for reading, and happy coding!

Источник

Оцените статью