How to Read and Append File in Python
In this tutorial, we are going to acquire how to read a file in Python iii. After nosotros have learned how to open a file in Python, we are going to larn how to write to the file and relieve information technology again. In previous posts, we take learned how to open a range of dissimilar files using Python. For example, we have learned how to open JSON, CSV, Excel, and HTML files using Pandas, and the json library. Here, nonetheless, we are going to open plain files (.txt) in Python.
Prerequisites
In this Python tutorial, we demand to have Python 3 installed. 1 of the easiest ways to install Python is to download a Python distribution, such as Anaconda, ActivePython, or Enthought Canopy, to proper noun a few. Here's a YouTube tutorial on how to install Anaconda.
Reading Files in Python
Now, when we are working with Python, there is no need to import a library in order to read and write files. Reading and writing files, in Python, is handled natively in the language.
In this post, we will, thus, focus on using Python to open a file and we will use the built-in open function to get a file object.
Python'south File Object
Now, when nosotros are using Python's open up office, it will render something known as a file object. These objects will contain methods and attributes that we can employ to gather information about the file we have opened (much similar we've learned when using Pandas dataframe objects, for instance). 1 slap-up thing, of course, is that we can use these methods to change the file that we have opened using Python.
In this Python read from a file tutorial, we are going to piece of work with the mode attribute. This attribute volition tell us which fashion the file nosotros accept opened, using Python, is in. Furthermore, the name attribute volition give united states the name of the file we have opened in Python (i.e., the proper name of the file object).
How do You Read a File in Python?
Opening, and reading, a file in Python is like shooting fish in a barrel: nosotros only type ourfile = open('PATH_TO_FILE') and so ourfile.read().
What Does read() Return in Python?
Now, if we open a file in Python the read() return a Python cord object.
How to Read a File in Python using the open() office
In this department, we are going to learn how to load a file in Python using the open() function. In information technology's simplest case, open() will open up a file and create a file object.
As tin be seen, in the image to a higher place, there are a couple of arguments that can be used, nonetheless, when opening a file using Pythons open() role. The virtually usually used arguments, however, are the first two. Notation, the first is mandatory and the rest of them are optional. If nosotros don't add a mode, the file volition be opened in read-only way in Python.
Using the mode argument when reading files in Python
In this section, of the post on how to read a file in Python, we will go through the different modes in which we tin read a file. As previously mentioned, if nosotros don't laissez passer anything with the fashion statement the file will be written in read-only. In this reading files in Python tutorial, we are going to work with the following modes:
That is, nosotros can open a file in read-but, write, suspend, and read and write mode. If we use append ('a') we will suspend information at the end of that file.
A Unproblematic Read a File in Python Instance
Now, nosotros are going to read a file in Python using only the file name every bit an argument. As axiomatic, in the code example beneath, open() takes a string with the file path as input. In this reading a file in Python example, it is assumed that the case file is in the same directory as the Python script. Or in this case, the Jupyter notebook.
# Reading and press a file in Python: exfile = open('example_file') print(exfile)
Code language: Python ( python )
In the image, above, information technology becomes evident that we take a file object that nosotros have opened in read-only mode. To iterate what nosotros did, nosotros opened upwardly the text file (example_file.txt) without whatsoever other arguments. This, in plough, leads to that the file was opened in the read fashion. Thus, we cannot write to that file. If we want to print the proper name of the file we can simply type print(exfile.proper name).
Creating a Text file and Writing to the File using Python
In the next how to read a file in Python example, we are going to create a file using Python open up(). Now, we are going to apply open with the write mode. That is, we are going to open a file object and then use the file objects write method.
# Creating a file in Python: exfile = open('example_file2', 'westward') impress(exfile)
Lawmaking language: Python ( python )
Writing to the File:
At present, in the paradigm in a higher place, we can encounter that we have a file object in write fashion ('w'). In the next code clamper, we are going to add one line of text to this file, Here is how to write a line to our created file:
# Writing a line to our file: exfile.write('This is example file 2 \n')
Code language: Python ( python ) If nosotros want to, we tin, of grade, add more lines by using the write method again:
# Writing a second line to the file: exfile.write('Line number 2, in case file 2') exfile.close()
Code language: Python ( python ) Notation, how we airtight the file using close() in the last line above. In the image, beneath, we can come across the example file we have created with Python.
How to Read a Text File in Python using open up()
In the next Python read a file example, we volition acquire how to open a text (.txt) file in Python. This is, of class, uncomplicated and we accept basically already the knowledge on how to do this with Python. That is if nosotros just want to read the .txt file in Python nosotros tin use open and the read mode:
# Python read .txt file: txtfile = open('example_file.txt')
Code language: Python ( python ) Opening a File in Python: read() Example:
This was simple. Now, if we want to print the content of the text file we have iii options. Commencement, we can use the read() method. This Python method will read the entire file. That is, txtfile.read() will give united states the following output:
Reading a File to a Python list: readlines() Instance:
If we, on the other mitt, want to read the content from a file to a Python list, we can use the readlines() method. That is if nosotros want to read the text file into a list nosotros type:
# Read the .txt file: txtfile = open('example_file.txt') # Reading the lines into a Python list: print(txtfile.readlines())
Lawmaking language: Python ( python )
Reading Specific Lines:
Furthermore, we can besides utilize the sizehint argument. This enables us to become certain lines. For example, the following code will read the two showtime lines, into two different cord variables, and impress it:
# Opening a file: txtfile = open('example_file.txt') # Reading a line: line = txtfile.readlines(i) impress(line) # Reding another line: line2 = txtfile.readlines(2) impress(line2)
Code language: Python ( python )
Finally, when nosotros accept opened a file in Python we tin also loop through the content and print line past line:
txtfile = open('example_file.txt') for line in txtfile: print(line)
Code language: Python ( python )
Reading a File in Python and Appending Content to It
In the next example, we are going to read a file in Python and append information to the file. More specifically, nosotros are going to load a .txt file using Python and append some data to it. Again, nosotros start past opening the file in Python using open() but using the append mode:
open('example_file2.txt', 'a')
Lawmaking language: JavaScript ( javascript ) Appending Text to the File:
Adjacent, we are going to add content to this using write(), again.
# Suspend a line to the file with Python: txtfile.write('\northward More text here.')
Code language: Python ( python ) When appending text, in Windows 10 at least, we have to add together the \north before the line or else this line volition be appended next to the last graphic symbol (on the last line, of the file). If we are to add more than lines, we take to recollect to practice this equally well;
# Appending a second lien to the file: txtfile.write('\nLast line of text, I promise.) # Recollect to close the file! txtfile.shut()
Code language: Python ( python ) Finally, we tin open the text file using a text editor (due east.thousand., Notepad, Gedit) and we'll see the last two lines that we've added:
How to Read a file in Python using the with Statement
In the next how to open a file in Python case, nosotros are going to read a file using the with statement. This has the advantage that we don't have to call up to close the file and the syntax for using the with statement is clean to read:
with open up('example_file2.txt') every bit txtfile2: print(txtfile2.read())
Code language: Python ( python )
ValueError: I/O operation on airtight file
Now, if we attempt to utilize the read() method Python volition throw a ValueError:
txtfile2 .read()
Lawmaking language: CSS ( css )
We get this ValueError because nosotros used the with() argument while opening the file.
Splitting Words in File and Counting Words
Every bit final reading a file in Python example, nosotros are going to use the string split() method to split the sentences in the text file into words. When we have read the file and split the words, nosotros are going to use the Counter subclass from collections to utilize Python to count words in an opened file.
from collections import Counter with open('example_file2.txt') as txtfile2: wordcount = Counter(txtfile2.read().split()) print(len(wordcount)) # Output: 43
Code language: Python ( python ) Counting Words in Python
Now, the Counter bracket is giving us a dictionary that contains all words and occurrences of each word. Thus, we can print all words and their count like this:
for k in sorted(wordcount, fundamental=wordcount.get, reverse=True): print(one thousand, wordcount[1000])
Code language: Python ( python ) In the lawmaking example above, nosotros are looping through the keys in the lexicon and sort them. This style, nosotros become the most common words on top. Of course, reading a file with many words, using Python, and printing the result like this is not feasible.
If we take the demand it is, of course, also possible to rename a file (or multiple files) in Python using the os.rename() method.
Reading other File Formats in Python
At present, we accept learned how to load a file in Python, and we volition briefly discuss other file formats that Python tin can handle. Python can, of course, open a broad range of different file formats. In previous posts, we have used the json library to parse JSON files in Python, for example. Furthermore, we accept also learned how to read csv files in Python using Pandas, open up Excel files with Pandas, amid other file formats that are common for storing data.
- See here for some examples of file formats Python can read.
Determination: Reading & Writing Files in Python
In this tutorial, nosotros accept learned the basics of how to open up files in Python. More specifically, we take learned how to read a file in different modes, create and write to a file, append data to a file, and how to read a file in Python using the with statement. In future posts, we will learn more than about how to read other file formats using Python (e.g., CSV, Excel).
Drib a annotate below if you demand annihilation covered in this or a future blog, and stay tuned!
Source: https://www.marsja.se/how-to-read-a-file-in-python-write-to-and-append-to-a-file/
0 Response to "How to Read and Append File in Python"
Publicar un comentario