How to Read the Contents of a File in Python



Python


In this article, we show how to read the contents of a file in Python.

It's relatively easy for Python to read files.

These include plaintext files, such as text files (.txt), html files (.html or .htm), PHP files (.php), etc.

These do not include more complex files such as binary files, such as Word documents and PDFs.

In order for Python to read those files, extra modules need to be in place.

In this article, we show how to read simple plaintext files, such as text files.

So the code to read the contents of a file is shown below.



So this is the process.

In order to read a file in Python, first you must open the file. So, you must use the open() function to first open the file. Inside of this open() function, you specify the file that you want to open. If the file is not located in the current working directory, you need to specify the full path to the file. If the file is located in the current working directory, then you can just enter the file directly, without specifying the path.

So now this openfile variable contains the File object of the file that we want to open.

We now have the File object, which represents the file.

We, then, next create another variable, readfile (you can name these anything you want). The readfile variable takes the File object, openfile, and reads it, with the read() function.

So now this readfile contains the contents of the file that we want to read.

Now, to output the contents of the file to the screen, we simply call the readfile variable.

This gives us the contents of the read file.

So, I created a file, called file.txt.

In the file is the statement, Today is going to be Sunny. You can see it here: file.

Running the above code gives us the following output.



So, this is all that is necessary in order to read the contents of a file in Python.

Again, this for simple plaintext files.


Related Resources



HTML Comment Box is loading comments...