What is Python File Reading?
Reading and writing files is an incredibly important skill since more often than not developers need to work with files of different formats when developing programs.
Text files, CSV files and JSON files are the most common types of files used in Python programs. Both JSON and CSV files require importing extra modules, unlike text files that we can just import in and out.
Managing files in Python
Having the files that we need to work within the same directory with the Python file that we are writing code allows us to reference them directly.
Managing files in Python can be a daunting task especially if we have to open and close the files manually. However, python provides us with the context manager that gives developers flexibility when managing resources in Python.
How to use Python File Reader methods?
There are two keywords that are important when working with the context manager, the keyword ‘with’ and ‘open(…)’. Now inside the parentheses that precede the word open(…), we’re going to give it the name of the file and how we want to open the file.
There are four different modes of opening files in python, we can open or read or write in bytes representation as enlisted below.
- “r” – Read – Open a file for reading (Default).
- “a” – Append – Opens a file for appending.
- “w” – Write – Opens a file for writing.
- “x” – Create – Creates the specified file.
In this case, we’re going to be using just reading. So inside our with open() statement here we will have quotes marks and then we type the name of the file.
Once we pass the name of the file that we intend to open which in this case is called ‘mytextfile.txt.’ we need to put a comma and then another quote mark and the ‘r’ for reading.
Using variables with the file open method
Now because we’re using the context manager then we need to give it a variable so that it’s going to open it as this variable. We can use ‘f’ which is the default value.
If we hit enter and move to the next indented line we will still be within the context manager, and in order to read the contents of the file, we need to do print(f.read).
Alternatively, we could save f.read into a variable and then print it outside the context manager instead, since the information will still be saved.
How to read CSV files with the Python File Reader?
Opening text files is useful but nowhere near as useful as opening CSV files. A CSV file is opened in a similar way, however, we need to import the CSV module first before we can start using CSV files.
The CSV module is in the standard library and therefore all that we need to do is import CSV. Then we’re going to do with open() in the same way as we did before and then pass in the name of the CSV file which is ‘csvinfo.csv’, and again, we’re going to be doing ‘r’ for read-only and again as f.
We need to create a variable again that is going to represent our CSV reader we are just going to call this one reader is equal to csv.reader(). Now, if we try to print out this reader object is going to tell us that this is a reader object.
Python file reader method with for loop
Now we can actually start to work with the file. A CSV file generally has rows so we’re going to do for row in the reader and we’re going to do a simple for loop through each one of those.
Once we print out the rows Python will turn each of the rows into a list that we have access to. The first row is made up of the row header followed by the rows that hold the data underneath.
How to read JSON files with Python File Reader
JSON file formats are also very common in programming. In order to work with JSON files in Python, we need to import the JSON library.
In a similar manner reading a JSON file begins by stating the two keywords with open(), before passing in the name of the JSON file that we intend to import which is ‘somejsondata.json’ and the state that we intend to access it i.e in the read-only mode we use ‘r’.
Using the JSON module
And now we need to use the JSON module that we have imported to load the JSON data into something that we can work with.
By stating as f at the end of the above statement we imply that we intend to store the file output as a variable, therefore we can create a variable ‘data’ and let it be equal to json.load(…).
Basically, this reads the JSON file from a text and thus we are also going to pass in the keyword ‘f’ within the parentheses.
Once we are done importing the JSON file we can now move the cursor to the outside of the context manager and print the variable data that now store the JSON file that we have loaded to the screen.
This is how to use the Python file reader methods in practice. If you’d like to see more programming tutorials, check out our Youtube channel, where we have plenty of Python video tutorials in English.
In our Python Programming Tutorials series, you’ll find useful materials which will help you improve your programming skills and speed up the learning process.
- How to use the Python for loop
- How to use Python Sets
- How to use a Python Dictionary
- How to use Python Classes
- How to use Python Range
- How to use Python if-else statements
- How to use Python RegEx
- How to use Python Lists
- How to use Python Enumerate
- How to use Python Functions
- How to use Python Split
- How to use Python Try-Except
- How to use Python Tuples
- How to use Python Arrays
- How to use Python Sort
- How to use the Python DateTime
- How to download Python?
- How to use the Python FileWrite function
- How to use Python Lambda
- How to use Python ListAppend
- How to use Python ListComprehension
- How to use Python Map
- How to use Python Operators
- How to use Python Pandas
- How to use Python Requests
- How to use Python Strings
- How to use Python Count
- How to use Python Comments
- How to use the Python File Reader method
- How to use the Python IDE-s
- How to use Python logging
- How to use Python Print
- How to use the Python Zip
- How to use Python Append
- How to use Python Global Variables
- How to use the Python join method
- How to use Python list length
- How to use Python JSON files
- How to use Python Modulo
- How to use Python file opening methods
- How to use Python round
- How to use Python sleep
- How to use Python replace
- How to use Python strip
- How to use the Python Time module
- How to use Python unittests
- How to save data to a text file using Context Manager?
- How to use Python external modules
- How to use Python find
- How to use the Python pip package manager
- How to delete files in Python
- Parsing XML files in Python
- How to make a GUI in Python
- How to use Python in Command Prompt
- How to Run a Python Program in VS Code
- How to run a program in Python IDLE
- How to run a program in Jupyter Notebook
- How to read a text file in Python
- How to add numbers in Python
- How to ask for user input in Python
- How to debug in Python
- How to create a thread in Python
- How to import a library in Python
- How to use the PIP package manager
- How to use classes in Python
- How to reverse strings in Python
- How to convert a string to int in Python
- How to print on the same line in Python
- How to remove items from a list
- How to add to a dictionary in Python
- How to raise an exception in Python
- How to throw an exception in Python
- How to stop a program in Python
- How to use Python assert
- How to use the Python compiler
Would you like to learn how to code, online? Come and try our first 25 lessons for free at the CodeBerry Programming School.