It has been renamed to GNUREADLINE to resolve a name clash with the
standard library module. Please go to the new gnureadline PyPI page.
Stand-alone readline module
Some platforms, such as Mac OS X, do not ship with GNU readline installed.
The readline extension module in the standard library of Mac “system” Python
uses NetBSD’s editline (libedit) library instead, which is a readline
replacement with a less restrictive software license.
As the alternatives to GNU readline do not have fully equivalent functionality,
it is useful to add proper readline support to these platforms. This module
achieves this by bundling the standard Python readline module with the GNU
readline source code, which is compiled and statically linked to it. The end
result is a package which is simple to install and requires no extra shared
libraries.
The module can be used with both Python 2.x and 3.x but only up to 3.3, and
has been tested with Python versions 2.5, 2.6, 2.7, 3.1, 3.2 and 3.3. The first
three numbers of the module version reflect the version of the underlying GNU
readline library (major, minor and patch level), while any additional fourth
number distinguishes different module updates based on the same readline library.
This module is usually unnecessary on Linux and other Unix systems with default
readline support. An exception is if you have a Python distribution that does
not include GNU readline due to licensing restrictions (such as ActiveState’s
ActivePython in the past). If you are using Windows, which also ships without
GNU readline, you might want to consider using the pyreadline module instead,
which is a readline replacement written in pure Python that interacts with the
Windows clipboard.
The latest development version is available from the GitHub repository.
History
6.2.4.2 (2022-06-24)
-
THIS PACKAGE IS DEPRECATED! USE gnureadline INSTEAD!
-
Add appropriate warnings to the docs to hammer this home
-
Prevent installation on Python 3.4 and later (the module is outdated)
-
Fix compilation on macOS 10.9+ to avoid crash before Python version check
6.2.4.1 (2012-10-22)
-
#21: Fixed building on Python.org 3.3 / Mac OS 10.8
6.2.4 (2012-10-17)
-
#15: Improved detection of compilers before Xcode 4.3
-
Uses Python 3.x readline.c from v3.3.0 tag (changeset 73997)
-
Updated to build against readline 6.2 (patch-level 4)
6.2.2 (2012-02-24)
-
#14: Fixed compilation with Xcode 4.3 on Mac OS 10.7
-
Updated to build against readline 6.2 (patch-level 2)
6.2.1 (2011-08-31)
-
#10: Fixed ‘_emacs_meta_keymap’ missing symbol on Mac OS 10.7
-
#7: Fixed SDK version check to work with Mac OS 10.7 and later
-
Uses Python 2.x readline.c from release27-maint branch (r87358)
-
Uses Python 3.x readline.c from release32-maint branch (r88446)
6.2.0 (2011-06-02)
-
#5: Removed ‘-arch ppc’ on Mac OS 10.6, as Snow Leopard supports Intel only
-
Updated to build against readline 6.2 (patch-level 1)
6.1.0 (2010-09-20)
-
Changed version number to reflect readline version instead of Python version
-
#4: Updated to build against readline 6.1 (patch-level 2)
-
#2: Python 3 support
-
Uses Python 2.x readline.c from release27-maint branch (r83672)
-
Uses Python 3.x readline.c from r32a2 tag (r84541)
-
Source code moved to GitHub
-
Additional maintainer: Sridhar Ratnakumar
2.6.4 (2009-11-26)
-
Added -fPIC to compiler flags to fix linking error on 64-bit Ubuntu
-
Enabled all readline functionality specified in pyconfig.h macros
-
Uses readline.c from Python svn trunk (r75725), which followed 2.6.4 release
-
Patched readline.c to replace Py_XDECREF calls with the safer Py_CLEAR
-
Fixed compilation error on Mac OS 10.4 with XCode older than version 2.4
2.6.1 (2009-11-18)
-
Updated package to work with Mac OS 10.6 (Snow Leopard), which ships with
Python 2.6.1 -
Uses readline.c from Python 2.6.1 release
-
Backported “spurious trailing space” bugfix from Python svn trunk (see e.g.
https://bugs.launchpad.net/python/+bug/470824 for details on bug) -
Updated to build against readline 6.0 (patch-level 4)
-
Now builds successfully on Linux (removed Mac-specific flags in this case),
and still supports Mac OS 10.4 and 10.5
2.5.1 (2008-05-28)
-
Updated package to work with Mac OS 10.5 (Leopard), which ships with Python
2.5.1 -
Uses readline.c from Python 2.5.1 release
-
Updated to build against readline 5.2 (patch-level 12)
-
New maintainer: Ludwig Schwardt
2.4.2 (2005-12-26)
-
Original package by Bob Ippolito, supporting Python 2.3 / 2.4 on Mac OS 10.3
(Panther) and 10.4 (Tiger) -
Builds against readline 5.1
pyreadline3
The pyreadline3
package is based on the stale package pyreadline
located
here.
The original pyreadline
package is a Python implementation of GNU readline
functionality.
It is based on the ctypes
based UNC readline
package by Gary Bishop.
It is not complete.
It has been tested for use with Windows 10.
Version 3.4+ of pyreadline3 runs on Python 3.8+.
pyreadline3
is available on PyPI and can be installed with
Features
- keyboard text selection and copy/paste
- Shift-arrowkeys for text selection
- Control-c can be used for copy activate with allow_ctrl_c(True) in config file
- Double tapping ctrl-c will raise a KeyboardInterrupt, use ctrl_c_tap_time_interval(x)
- where x is your preferred tap time window, default 0.3 s.
- paste pastes first line of content on clipboard.
- ipython_paste, pastes tab-separated data as list of lists or numpy array if all data is numeric
- paste_mulitline_code pastes multi line code, removing any empty lines.
The latest development version is always available at the project git
repository
Development
To clone the library for development:
git clone git@github.com:pyreadline3/pyreadline3.git
or
git clone https://github.com/pyreadline3/pyreadline3.git
Build The Virtual Environment
The current earliest Python version supported is 3.8
. You need to be able to create a virtual environment at this version to make sure any changes you make is combatible.
If you are using conda
:
conda create --prefix=.venv python=3.8 --yes
If you are using venv
, make sure you have the right base package:
>> python --version
Python 3.8.x
Once you verify your base Python, you can then create a virtual environment using:
virtualenv -p py3.8 .venv
Setup
Once you have created your virtual environment and made sure it is active in your current command line:
This should all the dependencies you need for developing into the library and also allow you to run the unit tests:
Debugging
WIP
As an ex-sysadmin, I’m in love with the Readline. In Powershell, we have its variation PSReadline. In Python REPL on Windows OS, I’ll show you the PyReadline and the PtPython.
PyReadline#
When you search on Internet, you will find many tutorials telling you to install a Python module called readline, but unfortunately, it’s not compatible on Windows OS :
> pip install readline
Collecting readline
Using cached https://files.pythonhosted.org/packages/f4/01/2cf081af8d880b44939a5f1b446551a7f8d59eae414277fd0c303757ff1b/readline-6.2.4.1.tar.gz
Complete output from command python setup.py egg_info:
error: this module is not meant to work on Windows
On Windows, the counterpart is PyReadline, install it by :
Here are the features of PyReadline : — keyboard text selection and copy/paste — Shift-arrowkeys for text selection — Control-c can be used for copy activate with allow_ctrl_c(True) in config file — Double tapping ctrl-c will raise a KeyboardInterrupt, use ctrl_c_tap_time_interval(x) where x is your preferred tap time window, default — 0.3 s. — paste pastes first line of content on clipboard. — ipython_paste, pastes tab-separated data as list of lists or numpy array if all data is numeric — paste_mulitline_code pastes multi line code, removing any empty lines.
Warning
PyReadline was used by IPython, but since it hasn’t been maintained since 2015, IPython removed it, and replaced it by prompt_toolkit.
As PyReadline must be used inside Python REPL, you need to type import PyReadline
from the very beginning of the Python REPL. To be a lazy devops, just add the import into a file and let Python to source it before the first prompt is displayed by using $env:PYTHONSTARTUP :
# In powershell console
Add-Content $env:USERPROFILE/.pythonrc "`nimport PyReadline"
$env:PYTHONSTARTUP = "$env:USERPROFILE/.pythonrc"
PtPython#
Previous chapter mentioned that PyReadline is no more maintained, so here comes the PtPython.
PyPython is an interactive Python Shell, build on top of prompt_toolkit written by the same author Jonathan Slenders.
Install PtPython by :
Start it by typing simply : ptpython
from the terminal, it will start a Python REPL with prompt_toolkit integrated, nothing to set on $env:USERPROFILE
Purpose: | Provides an interface to the GNU readline library for interacting with the user at a command prompt. |
---|
The readline
module can be used to enhance interactive command
line programs to make them easier to use. It is primarily used to
provide command line text completion, or “tab completion”.
Note
Because readline
interacts with the console content,
printing debug messages makes it difficult to see what is
happening in the sample code versus what readline is doing for
free. The following examples use the logging
module to
write debug information to a separate file. The log output is
shown with each example.
Note
The GNU libraries needed for readline
are not available on
all platforms by default. If your system does not include them,
you may need to recompile the Python interpreter to enable the
module, after installing the dependencies. A stand-alone version of
the library is also distributed from the Python Package Index under
the name gnureadline. The examples in this section first try to
import gnureadline, and then fall back to readline.
Special thanks to Jim Baker for pointing out this package.
Configuring¶
There are two ways to configure the underlying readline library, using
a configuration file or the parse_and_bind()
function.
Configuration options include the key-binding to invoke completion,
editing modes (vi
or emacs
), and many other
values. Refer to the documentation for the GNU readline library for
details.
The easiest way to enable tab-completion is through a call to
parse_and_bind()
. Other options can be set at the same time.
This example changes the editing controls to use “vi” mode instead of
the default of “emacs”. To edit the current input line, press ESC
then use normal vi
navigation keys such as j
, k
,
l
, and h
.
readline_parse_and_bind.py¶
try: import gnureadline as readline except ImportError: import readline readline.parse_and_bind('tab: complete') readline.parse_and_bind('set editing-mode vi') while True: line = input('Prompt ("stop" to quit): ') if line == 'stop': break print('ENTERED: {!r}'.format(line))
The same configuration can be stored as instructions in a file read by
the library with a single call. If myreadline.rc
contains
myreadline.rc¶
# Turn on tab completion tab: complete # Use vi editing mode instead of emacs set editing-mode vi
the file can be read with read_init_file()
readline_read_init_file.py¶
try: import gnureadline as readline except ImportError: import readline readline.read_init_file('myreadline.rc') while True: line = input('Prompt ("stop" to quit): ') if line == 'stop': break print('ENTERED: {!r}'.format(line))
Completing Text¶
This program has a built-in set of possible commands and uses
tab-completion when the user is entering instructions.
readline_completer.py¶
try: import gnureadline as readline except ImportError: import readline import logging LOG_FILENAME = '/tmp/completer.log' logging.basicConfig( format='%(message)s', filename=LOG_FILENAME, level=logging.DEBUG, ) class SimpleCompleter: def __init__(self, options): self.options = sorted(options) def complete(self, text, state): response = None if state == 0: # This is the first time for this text, # so build a match list. if text: self.matches = [ s for s in self.options if s and s.startswith(text) ] logging.debug('%s matches: %s', repr(text), self.matches) else: self.matches = self.options[:] logging.debug('(empty input) matches: %s', self.matches) # Return the state'th item from the match list, # if we have that many. try: response = self.matches[state] except IndexError: response = None logging.debug('complete(%s, %s) => %s', repr(text), state, repr(response)) return response def input_loop(): line = '' while line != 'stop': line = input('Prompt ("stop" to quit): ') print('Dispatch {}'.format(line)) # Register the completer function OPTIONS = ['start', 'stop', 'list', 'print'] readline.set_completer(SimpleCompleter(OPTIONS).complete) # Use the tab key for completion readline.parse_and_bind('tab: complete') # Prompt the user for text input_loop()
The input_loop()
function reads one line after another
until the input value is "stop"
. A more sophisticated program
could actually parse the input line and run the command.
The SimpleCompleter
class keeps a list of “options” that are
candidates for auto-completion. The complete()
method for an
instance is designed to be registered with readline
as the
source of completions. The arguments are a text
string to complete
and a state
value, indicating how many times the function has been
called with the same text. The function is called repeatedly with the
state incremented each time. It should return a string if there is a
candidate for that state value or None
if there are no more
candidates. The implementation of complete()
here looks for a
set of matches when state is 0
, and then returns all of the
candidate matches one at a time on subsequent calls.
When run, the initial output is:
$ python3 readline_completer.py Prompt ("stop" to quit):
Pressing TAB
twice causes a list of options to be printed.
$ python3 readline_completer.py Prompt ("stop" to quit): list print start stop Prompt ("stop" to quit):
The log file shows that complete()
was called with two separate
sequences of state values.
$ tail -f /tmp/completer.log (empty input) matches: ['list', 'print', 'start', 'stop'] complete('', 0) => 'list' complete('', 1) => 'print' complete('', 2) => 'start' complete('', 3) => 'stop' complete('', 4) => None (empty input) matches: ['list', 'print', 'start', 'stop'] complete('', 0) => 'list' complete('', 1) => 'print' complete('', 2) => 'start' complete('', 3) => 'stop' complete('', 4) => None
The first sequence is from the first TAB key-press. The completion
algorithm asks for all candidates but does not expand the empty input
line. Then on the second TAB, the list of candidates is recalculated
so it can be printed for the user.
If the next input is “l
” followed by another TAB, the screen
shows:
Prompt ("stop" to quit): list
and the log reflects the different arguments to complete()
:
'l' matches: ['list'] complete('l', 0) => 'list' complete('l', 1) => None
Pressing RETURN now causes input()
to return the value, and the
while
loop cycles.
Dispatch list Prompt ("stop" to quit):
There are two possible completions for a command beginning with
“s
”. Typing “s
”, then pressing TAB finds that “start
” and
“stop
” are candidates, but only partially completes the text on
the screen by adding a “t
”.
The log file shows:
's' matches: ['start', 'stop'] complete('s', 0) => 'start' complete('s', 1) => 'stop' complete('s', 2) => None
and the screen:
Prompt ("stop" to quit): st
Note
If a completer function raises an exception, it is ignored
silently and readline
assumes there are no matching
completions.
Accessing the Completion Buffer¶
The completion algorithm in SimpleCompleter
only looks at the text
argument passed to the function, but does not use any more of
readline’s internal state. It is also possible to use readline
functions to manipulate the text of the input buffer.
readline_buffer.py¶
try: import gnureadline as readline except ImportError: import readline import logging LOG_FILENAME = '/tmp/completer.log' logging.basicConfig( format='%(message)s', filename=LOG_FILENAME, level=logging.DEBUG, ) class BufferAwareCompleter: def __init__(self, options): self.options = options self.current_candidates = [] def complete(self, text, state): response = None if state == 0: # This is the first time for this text, # so build a match list. origline = readline.get_line_buffer() begin = readline.get_begidx() end = readline.get_endidx() being_completed = origline[begin:end] words = origline.split() logging.debug('origline=%s', repr(origline)) logging.debug('begin=%s', begin) logging.debug('end=%s', end) logging.debug('being_completed=%s', being_completed) logging.debug('words=%s', words) if not words: self.current_candidates = sorted( self.options.keys() ) else: try: if begin == 0: # first word candidates = self.options.keys() else: # later word first = words[0] candidates = self.options[first] if being_completed: # match options with portion of input # being completed self.current_candidates = [ w for w in candidates if w.startswith(being_completed) ] else: # matching empty string, # use all candidates self.current_candidates = candidates logging.debug('candidates=%s', self.current_candidates) except (KeyError, IndexError) as err: logging.error('completion error: %s', err) self.current_candidates = [] try: response = self.current_candidates[state] except IndexError: response = None logging.debug('complete(%s, %s) => %s', repr(text), state, response) return response def input_loop(): line = '' while line != 'stop': line = input('Prompt ("stop" to quit): ') print('Dispatch {}'.format(line)) # Register our completer function completer = BufferAwareCompleter({ 'list': ['files', 'directories'], 'print': ['byname', 'bysize'], 'stop': [], }) readline.set_completer(completer.complete) # Use the tab key for completion readline.parse_and_bind('tab: complete') # Prompt the user for text input_loop()
In this example, commands with sub-options are being completed.
The complete()
method needs to look at the position of the
completion within the input buffer to determine whether it is part of
the first word or a later word. If the target is the first word, the
keys of the options dictionary are used as candidates. If it is not
the first word, then the first word is used to find candidates from
the options dictionary.
There are three top-level commands, two of which have sub-commands.
- list
- files
- directories
- print
- byname
- bysize
- stop
Following the same sequence of actions as before, pressing TAB twice
gives the three top-level commands:
$ python3 readline_buffer.py Prompt ("stop" to quit): list print stop Prompt ("stop" to quit):
and in the log:
origline='' begin=0 end=0 being_completed= words=[] complete('', 0) => list complete('', 1) => print complete('', 2) => stop complete('', 3) => None origline='' begin=0 end=0 being_completed= words=[] complete('', 0) => list complete('', 1) => print complete('', 2) => stop complete('', 3) => None
If the first word is "list "
(with a space after the word), the
candidates for completion are different.
Prompt ("stop" to quit): list directories files
The log shows that the text being completed is not the full line,
but the portion after list
.
origline='list ' begin=5 end=5 being_completed= words=['list'] candidates=['files', 'directories'] complete('', 0) => files complete('', 1) => directories complete('', 2) => None origline='list ' begin=5 end=5 being_completed= words=['list'] candidates=['files', 'directories'] complete('', 0) => files complete('', 1) => directories complete('', 2) => None
Input History¶
readline
tracks the input history automatically. There are two
different sets of functions for working with the history. The history
for the current session can be accessed with
get_current_history_length()
and get_history_item()
. That
same history can be saved to a file to be reloaded later using
write_history_file()
and read_history_file()
. By default
the entire history is saved but the maximum length of the file can be
set with set_history_length()
. A length of -1 means no limit.
readline_history.py¶
try: import gnureadline as readline except ImportError: import readline import logging import os LOG_FILENAME = '/tmp/completer.log' HISTORY_FILENAME = '/tmp/completer.hist' logging.basicConfig( format='%(message)s', filename=LOG_FILENAME, level=logging.DEBUG, ) def get_history_items(): num_items = readline.get_current_history_length() + 1 return [ readline.get_history_item(i) for i in range(1, num_items) ] class HistoryCompleter: def __init__(self): self.matches = [] def complete(self, text, state): response = None if state == 0: history_values = get_history_items() logging.debug('history: %s', history_values) if text: self.matches = sorted( h for h in history_values if h and h.startswith(text) ) else: self.matches = [] logging.debug('matches: %s', self.matches) try: response = self.matches[state] except IndexError: response = None logging.debug('complete(%s, %s) => %s', repr(text), state, repr(response)) return response def input_loop(): if os.path.exists(HISTORY_FILENAME): readline.read_history_file(HISTORY_FILENAME) print('Max history file length:', readline.get_history_length()) print('Startup history:', get_history_items()) try: while True: line = input('Prompt ("stop" to quit): ') if line == 'stop': break if line: print('Adding {!r} to the history'.format(line)) finally: print('Final history:', get_history_items()) readline.write_history_file(HISTORY_FILENAME) # Register our completer function readline.set_completer(HistoryCompleter().complete) # Use the tab key for completion readline.parse_and_bind('tab: complete') # Prompt the user for text input_loop()
The HistoryCompleter
remembers everything typed, and uses
those values when completing subsequent inputs.
$ python3 readline_history.py Max history file length: -1 Startup history: [] Prompt ("stop" to quit): foo Adding 'foo' to the history Prompt ("stop" to quit): bar Adding 'bar' to the history Prompt ("stop" to quit): blah Adding 'blah' to the history Prompt ("stop" to quit): b bar blah Prompt ("stop" to quit): b Prompt ("stop" to quit): stop Final history: ['foo', 'bar', 'blah', 'stop']
The log shows this output when the “b
” is followed by two TABs.
history: ['foo', 'bar', 'blah'] matches: ['bar', 'blah'] complete('b', 0) => 'bar' complete('b', 1) => 'blah' complete('b', 2) => None history: ['foo', 'bar', 'blah'] matches: ['bar', 'blah'] complete('b', 0) => 'bar' complete('b', 1) => 'blah' complete('b', 2) => None
When the script is run the second time, all of the history is read
from the file.
$ python3 readline_history.py Max history file length: -1 Startup history: ['foo', 'bar', 'blah', 'stop'] Prompt ("stop" to quit):
There are functions for removing individual history items and clearing
the entire history, as well.
Hooks¶
There are several hooks available for triggering actions as part of
the interaction sequence. The startup hook is invoked immediately
before printing the prompt, and the pre-input hook is run after the
prompt, but before reading text from the user.
readline_hooks.py¶
try: import gnureadline as readline except ImportError: import readline def startup_hook(): readline.insert_text('from startup_hook') def pre_input_hook(): readline.insert_text(' from pre_input_hook') readline.redisplay() readline.set_startup_hook(startup_hook) readline.set_pre_input_hook(pre_input_hook) readline.parse_and_bind('tab: complete') while True: line = input('Prompt ("stop" to quit): ') if line == 'stop': break print('ENTERED: {!r}'.format(line))
Either hook is a potentially good place to use insert_text()
to
modify the input buffer.
$ python3 readline_hooks.py Prompt ("stop" to quit): from startup_hook from pre_input_hook
If the buffer is modified inside the pre-input hook, redisplay()
must be called to update the screen.
See also
- Standard library documentation for readline
- GNU readline –
Documentation for the GNU readline library. - readline init file format
– The initialization and configuration file format. - effbot: The readline module –
Effbot’s guide to the readline module. - gnureadline – A statically linked version of
readline
available for many platforms and installable viapip
. - pyreadline – pyreadline,
developed as a Python-based replacement for readline to be used
on Windows. cmd
– Thecmd
module usesreadline
extensively to
implement tab-completion in the command interface. Some of the
examples here were adapted from the code incmd
.rlcompleter
–rlcompleter
usesreadline
to add
tab-completion to the interactive Python interpreter.
Python предоставляет множество встроенных функций для выполнения различных операций с файлами, таких как создание, чтение и запись в текстовые файлы. Python может обрабатывать в основном два типа файлов: обычные текстовые файлы и бинарные файлы. В этом гайде мы разберемся, как читать текстовые файлы в Python.
Для чтения текстового файла в Python необходимо выполнить следующие шаги:
-
Шаг 1: Файл необходимо открыть для чтения с помощью метода open() и передать путь к файлу в функцию.
-
Шаг 2: Следующий шаг — чтение файла, и это можно сделать с помощью нескольких встроенных методов, таких как read(), readline(), readlines().
-
Шаг 3: После выполнения операции чтения, текстовый файл необходимо закрыть с помощью функции close().
Теперь, когда мы рассмотрели шаги для чтения содержимого файла, давайте разберемся с каждым из этих методов, прежде чем переходить к примерам.
Функция open() в Python
Функция open() открывает файл, если это возможно, и возвращает соответствующий объект файла.
Синтаксис выглядит так: open(file, mode=’r’, buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
Функция open() имеет много параметров. Давайте рассмотрим самые необходимые параметры для чтения текстового файла. Данная функция открывает файл в заданном режиме и возвращает объект файла.
Параметры
file – объект, который представляет путь к файлу
mode (опционально) – является необязательным параметром. Это строка, которая указывает режим, в котором вы хотите открыть файл.
Режим |
Описание |
‘r’ |
Открыть файл для чтения (если режим прямо не задан, то это режим используется по умолчанию). |
‘w’ |
Открыть файл для записи. Python создаст новый файл, если он не существует, или очистит содержимое файла, если он существует. |
‘x’ |
Открыть файл для эксклюзивного создания. (Если файл уже существует — исключение). |
‘a’ |
Открыть файл для добавления текста. Создает новый файл, если файл не существует. |
‘t’ |
Открыть файл в текстовом режиме. (режим по умолчанию) |
‘b’ |
Открыть файл в бинарном режиме. |
‘+’ |
Открыть файл для обновления (чтение и запись). |
Пример
file = open('C:\hellouser.txt','r')
Методы чтения содержимого файла
Существует три способа чтения данных из текстового файла.
-
read() : Функция read() возвращает прочитанные символы в виде строки. Этот метод хорош, когда у вас небольшой файл, и вы хотите прочитать определенное количество символов или весь файл и сохранить их в строковой переменной.
-
readline() : Функция **readline() **возвращает одну строку из текстового файла в виде строки.
-
readlines(): Функция **readlines() **считывает все строки из текстового файла и возвращает каждую строку как строковый элемент в списке.
Функция Python close()
В Python файл останется открытым до тех пор, пока вы не закроете файл с помощью функции close(). Хорошей практикой является выполнение этой операции после чтения данных из файла, поскольку это освобождает пространство памяти, занимаемое этим файлом.
Примеры чтения текстового файла в Python
Пример 1 — чтение текстового файла с помощью функции read()
В приведенном ниже примере мы читаем весь текстовый файл с помощью метода read(). Файл можно открыть в режиме чтения или в текстовом режиме для чтения данных, и его можно сохранить в строковой переменной.
# Программа для чтения всего файла с использованием функции read()
file = open("hellouser.txt", "r")
content = file.read()
print(content)
file.close()
# Программа для чтения всего файла (полный путь) с помощью функции read()
file = open("C:/Projects/Pythontextreading/hellouser.txt", "r")
content = file.read()
print(content)
file.close()
Результат
Dear User,
Welcome to this guide!
Thank you for reading.
I hope it is helpful for you!
Kind regards,
Valentin Shashkin
Пример 2 – Чтение определенного количества символов в текстовом файле с помощью функции read()
Иногда вам необходимо прочитать определенное количество символов в файле. В этом случае вы можете использовать функцию read(), указав количество символов, которое необходимо. Метод выведет только указанное количество символов в файле, как показано ниже.
# Программа для чтения определенного количества
# символов в файле с помощью функции read()
file = open("hellouser.txt", "r")
content = file.read(20)
print(content)
file.close()
Результат
Dear User,
Welcome
Пример 3 – Чтение одной строки в файле с помощью функции readline()
Если вам необходимо прочитать только одну строку в файле, то вы можете сделать это с помощью функции readline(). Вы также можете использовать этот метод для извлечения определенного количества символов в строке, аналогично методу read().
# Программа для чтения одной строки в файле с помощью
file = open("hellouser.txt", "r")
content = file.readline()
print(content)
file.close()
Результат
Dear User,
Пример 4. Чтение текстового файла построчно с помощью функции readline()
Если вы хотите пройти по файлу построчно и вывести в любом формате, то вы можете использовать цикл while с методом readline(), как показано ниже. Это наиболее эффективный способ чтения текстового файла построчно в Python.
# Программа для чтения всех строк в файле с помощью функции readline()
file = open("hellouser.txt", "r")
while True:
content=file.readline()
if not content:
break
print(content)
file.close()
Результат
Dear User,
Welcome to this guide!
Thank you for reading.
I hope it is helpful for you!
Kind regards,
Valentin Shashkin
Пример 5 – Прочитать все строки в виде списка в файле с помощью функции readlines()
Метод readlines() прочитает все строки в файле и выведет строки в виде списка, как показано ниже. Далее, вы сможете проходить по этому списку для извлечения требуемого содержимого.
# Программа для чтения всех строк в виде списка в файле
# с использованием функции readlines()
file = open("hellouser.txt", "r")
content=file.readlines()
print(content)
file.close()
Результат
['Dear User,\n', 'Welcome to this guide!\n', 'Thank you for reading.\n', 'I hope it is helpful for you!\n', 'Kind regards,\n', 'Valentin Shashkin']
Желаю Вам успехов в обучении и надеюсь, что этот короткий гайд вам помог!