How to Read a Portion of a File in Python
Summary: in this tutorial, you lot learn diverse ways to read text files in Python.
TL;DR
The post-obit shows how to read all texts from the readme.txt
file into a cord:
with open up('readme.txt') as f: lines = f.readlines()
Code language: JavaScript ( javascript )
Steps for reading a text file in Python
To read a text file in Python, yous follow these steps:
- First, open a text file for reading past using the
open up()
office. - Second, read text from the text file using the file
read()
,readline()
, orreadlines()
method of the file object. - Tertiary, close the file using the file
shut()
method.
1) open() part
The open()
part has many parameters but you'll be focusing on the kickoff ii.
open(path_to_file, mode)
The path_to_file
parameter specifies the path to the text file.
If the file is in the aforementioned binder as the program, yous only need to specify the name of the file. Otherwise, you need to specify the path to the file.
To specify the path to the file, you utilise the forward-slash ('/'
) fifty-fifty if you're working in Windows.
For example, if the file is readme.txt
stored in the sample folder as the programme, yous need to specify the path to the file every bit c:/sample/readme.txt
The mode
is an optional parameter. Information technology's a string that specifies the fashion in which you want to open up the file.
The post-obit table shows available modes for opening a text file:
Mode | Description |
---|---|
'r' | Open up for text file for reading text |
'due west' | Open a text file for writing text |
'a' | Open a text file for appending text |
For example, to open a file whose name is the-zen-of-python.txt
stored in the same folder equally the programme, you use the following lawmaking:
f = open up('the-zen-of-python.txt','r')
Code linguistic communication: JavaScript ( javascript )
The open up()
part returns a file object which you will use to read text from a text file.
ii) Reading text methods
The file object provides y'all with three methods for reading text from a text file:
-
read()
– read all text from a file into a cord. This method is useful if you have a small file and you want to dispense the whole text of that file. -
readline()
– read the text file line by line and return all the lines as strings. -
readlines()
– read all the lines of the text file and render them as a listing of strings.
3) close() method
The file that y'all open up volition remain open until you lot shut it using the close() method.
Information technology'southward of import to shut the file that is no longer in employ. If you don't close the file, the program may crash or the file would be corrupted.
The following shows how to call the close()
method to shut the file:
f .close()
Code language: CSS ( css )
To close the file automatically without calling the close()
method, you use the with
statement like this:
with open up(path_to_file) as f: contents = f.readlines()
Code language: JavaScript ( javascript )
In practice, you'll employ the with
argument to close the file automatically.
Reading a text file examples
We'll use the-zen-of-python.txt file for the demonstration.
The following example illustrates how to employ the read()
method to read all the contents of the the-zen-of-python.txt
file into a string:
with open up('the-zen-of-python.txt') as f: contents = f.read() print(contents)
Code language: JavaScript ( javascript )
Output:
Cute is better than ugly. Explicit is better than implicit. Simple is better than complex. ...
The following case uses the readlines()
method to read the text file and returns the file contents as a list of strings:
lines = [] with open('the-zen-of-python.txt') equally f: lines = f.readlines() count = 0 for line in lines: count += 1 print(f'line {count}: {line}')
Code linguistic communication: JavaScript ( javascript )
Output:
line one: Cute is better than ugly. line 2: Explicit is ameliorate than implicit. line three: Simple is better than complex. ...
The post-obit case shows how to utilize the readline()
to read the text file line past line:
with open('the-zen-of-python.txt') as f: line = f.readline() while line: line = f.readline() print(line)
Code language: JavaScript ( javascript )
Output:
Explicit is improve than implicit. Simple is better than complex. Complex is meliorate than complicated. ...
A more curtailed style to read a text file line past line
The open()
role returns a file object which is an iterable object. Therefore, yous can employ a for
loop to iterate over the lines of a text file as follows:
with open('the-zen-of-python.txt') as f: for line in f: impress(line)
Code language: JavaScript ( javascript )
This is more concise way to read a text file line by line.
Read UTF-8 text files
The code in the previous examples works fine with ASCII text files. However, if you're dealing with other languages such as Japanese, Chinese, and Korean, the text file is not a uncomplicated ASCII text file. And information technology'due south likely a UTF-8 file that uses more than than just the standard ASCII text characters.
To open a UTF-8 text file, you demand to pass the encoding='utf-8'
to the open up()
function to instruct it to expect UTF-8 characters from the file.
For the demonstration, you'll use the following quotes.txt
file that contains some quotes in Japanese.
The following shows how to loop through the quotes.txt
file:
with open('quotes.txt', encoding='utf8') as f: for line in f: print(line.strip())
Code linguistic communication: JavaScript ( javascript )
Output:
Summary
- Use the
open()
function with the'r'
mode to open a text file for reading. - Utilize the
read()
,readline()
, orreadlines()
method to read a text file. - E'er close a file after completing reading it using the
close()
method or thewith
argument. - Utilize the
encoding='utf-8'
to read the UTF-8 text file.
Did you discover this tutorial helpful ?
Source: https://www.pythontutorial.net/python-basics/python-read-text-file/
0 Response to "How to Read a Portion of a File in Python"
Enregistrer un commentaire