What is a text file?
A text file is a computer file that is structured as lines of electronic text.. For the purposes of programming and Python, it is a file containing a single string-type data object. Generally, it is also encoded by the computer and must be decoded before it can be parsed by a program. However, many different encodings can be used, and you can’t always tell which encoding has been used by just looking at the file. Encoding, however, is quite complicated and if you are new to it then all you need to know for this article is that the most common form of encoding is “UTF-8”. You can safely assume any file you encounter will be UTF-8 encoded, although this is not guaranteed. You can read more about encoding in this Real Python encodings guide for more information.Text file types
In both your professional and personal life, you encounter four common types of text files. These files contain plain text, but their distinct extensions indicate the various conventions they use to structure their data.From this point on we will refer to the category of file as “text files” and files that have the extension.txtastxtfiles in reference to the extension.
.txtfiles have no set convention and is the “generic” extension..csvfiles are “comma separated variable/value” files and typically contain data in columns, separated by the comma,delimiter (or sometimes the semicolon delimiter as well;)..tsvfiles are a close relation, but the “t” here stands for “tab”.
.json. “JavaScript Object Notation” files structure data as key-value pairs contained within pairs of{}. They look like Python dictionaries..xml. “eXtensible Markup Language” files structure data using angle brackets<>and are the hardest to work with in Python. HTML looks very similar, but isn’t the same.
.txt, provide the computer with information about the type of file it is processing and how to interpret it. This is normally hidden to the user. When you are writing code, however, you are explicitly taking control of how the file is handled. This means you can treat ANY file as a text file if you want to, regardless of its extension. And the reverse applies too: a file doesn’t have to have the .txt extension to be a text file.
We can treat all four of the types above as pure text files and simply process their context in different ways. In addition, some files may not have the expected extension, but can still be interpreted on the basis of their internal structure. For example, jupyter notebooks .ipynb files are JSON files and can be treated like JSON files.*
Working with text files in Python
The first step when working with any file in Python is to open it (and the last step should be to close it!). Working with files is like working with boxes. You have to open the box before you can take anything out of it. All Python text files can be opened in one of these two methods:- Explicitly open the file object, read the file, then close the file again after.
- use the
withstatement which automatically opens the file when the program enters the indented block and auto-closes it when the program leaves it.- This makes it less likely that one will forget the closing statement as it is built into the opening statement.
- Learn more about the
withpattern at Real Python: Python’s “with open() as” Pattern.
numpy or pandas, however, the same process is still going on behind the scenes, it’s just hidden in the functions you use.
These methods open the file, and parse the entire file as a single string. This can be useful but often you want to split the file into different lines or something else entirely. The file object has several methods available to cover common use cases.
file_object.read()- read the file as a single string and return that string.file_object.readlines()- reads all the lines in the file and returns a list of strings.file_object.readline()- reads ONE line of the file and returns it as a string. Can be called sequentially to parse lines in sequence.
my_txt.txt contains:
split and strip.
So, for example if you want to parse a text file into a list of strings (one per line) and strip out all the newline characters (\n) at the end of each line (a common thing to do), the following recipe will do just that.
\n! Strings and Character Data in Python is a great article in RealPython that covers the intricacies of characters and strings in Python and it worth a read for further information.
Working with CSV files in Python
CSV files are a bit easier to work with, since there are several good libraries you can use to help. In particular there’s the built-in librarycsv and the external, but common, libraries numpy and pandas.
csv
The csv library is fairly simple to use and will do the stripping of unwanted characters and the splitting up of the strings for you. However, it will not interpret the correct types for you. You still have to do that yourself. For example if your csv file (my_csv.csv) looks like:
column1 and column2:
numpy
The numpy library is even easier and does even more for you, but you need to be careful about the limitations it has, because its methods are not as flexible. For example, numpy arrays must all contain the same type and csv files parsed by numpy must be of a consistent shape. Lines of different lengths will cause problems and numpy can’t handle them. However, csv data doesn’t usually have these issues.
numpy array containing the data in the csv as floats, whilst skipping the header.
pandas
The pandas library is even easier and parses the csv file into a dataframe, but now the datatype needs to be consistent within a column, but not the file itself. Plus you can use the headers as labels in the dataframe. The downside is you still need rectangular data; uneven inputs per line will cause issues. You do also need to learn how to use dataframes, which are useful to know about but are another layer to learn.
This makes our code look even more concise.
data is now a dataframe containing the csv data.
Working with JSON files
JSON files are very similar to dictionaries in Python. They are key:value pairs with no defined schema within pairs of{}. All JSON files can be interpreted as Python dictionaries but not all Python dictionaries can be turned into (“serialized”) as JSON objects. You can use the builtin library json to work with JSON files in Python.
For example, if your JSON file (my_json.json) looks like:
data to screen, you can see:
Working with XML files
XML is the trickiest to work with as XML schemas can vary enormously and they don’t translate seamlessly into Python like JSON does. People sometimes try to do it with regular expressions. Don’t do this. XML is hierarchical. You have a root node and then that node will have child nodes which can have their own children and so on and so forth… Each node can possess key-value pairs of attributes, and a value. For example, a simple XML file (my_xml.xml) looks like:
ElementTree module. The following Python code parses the XML data into two lists named number1 and number2. Note that you access the children of a node by iterating over the parent node.
number nodes by accessing the attrib property.