Введення / виведення файлів Python: читання та запис файлів у Python

У цьому посібнику ви дізнаєтесь про файлові операції Python. Більш конкретно, відкриття файлу, читання з нього, запис у нього, закриття та різні методи файлів, про які вам слід знати.

Відео: Читання та запис файлів на Python

Файли

Файли називаються місцями на диску для зберігання відповідної інформації. Вони використовуються для постійного зберігання даних у енергонезалежній пам'яті (наприклад, на жорсткому диску).

Оскільки оперативна пам’ять (ОЗП) є мінливою (втрачає свої дані при вимкненому комп’ютері), ми використовуємо файли для подальшого використання даних, постійно зберігаючи їх.

Коли ми хочемо читати з файлу або писати у файл, нам потрібно спочатку його відкрити. Коли ми закінчимо, його потрібно закрити, щоб звільнити ресурси, пов’язані з файлом.

Отже, у Python файлова операція відбувається в такому порядку:

  1. Відкрийте файл
  2. Читання або запис (виконати операцію)
  3. Закрийте файл

Відкриття файлів у Python

Python має вбудовану open()функцію відкриття файлу. Ця функція повертає об'єкт файлу, який також називається дескриптором, оскільки він використовується для читання або модифікації файлу відповідно.

 >>> f = open("test.txt") # open file in current directory >>> f = open("C:/Python38/README.txt") # specifying full path

Ми можемо вказати режим під час відкриття файлу. У режимі ми вказуємо, чи хочемо ми читати r, писати wчи додавати aфайл. Ми також можемо вказати, чи хочемо ми відкрити файл у текстовому або двійковому режимі.

Типовим є читання в текстовому режимі. У цьому режимі ми отримуємо рядки під час читання з файлу.

З іншого боку, двійковий режим повертає байти, і саме цей режим буде використовуватися при роботі з нетекстовими файлами, такими як зображення або виконувані файли.

Режим Опис
r Відкриває файл для читання. (за замовчуванням)
w Відкриває файл для запису. Створює новий файл, якщо він не існує, або скорочує файл, якщо він існує.
x Відкриває файл для ексклюзивного створення. Якщо файл уже існує, операція не вдається.
a Відкриває файл для додавання в кінці файлу, не зменшуючи його. Створює новий файл, якщо він не існує.
t Відкривається в текстовому режимі. (за замовчуванням)
b Відкривається в двійковому режимі.
+ Відкриває файл для оновлення (читання та запис)
 f = open("test.txt") # equivalent to 'r' or 'rt' f = open("test.txt",'w') # write in text mode f = open("img.bmp.webp",'r+b') # read and write in binary mode

На відміну від інших мов, символ aне означає цифру 97, доки він не закодований за допомогою ASCII(або інших еквівалентних кодувань).

Більше того, кодування за замовчуванням залежить від платформи. У Windows це є, cp1252але utf-8в Linux.

Отже, ми також не повинні покладатися на кодування за замовчуванням, інакше наш код буде поводитися по-різному на різних платформах.

Отже, при роботі з файлами в текстовому режимі настійно рекомендується вказати тип кодування.

 f = open("test.txt", mode='r', encoding='utf-8')

Закриття файлів у Python

Коли ми закінчимо виконувати операції з файлом, нам потрібно правильно закрити файл.

Закриття файлу звільнить ресурси, пов’язані з файлом. Це робиться за допомогою close()методу, доступного в Python.

У Python є збирач сміття для очищення об'єктів без посилань, але ми не повинні покладатися на нього, щоб закрити файл.

 f = open("test.txt", encoding = 'utf-8') # perform file operations f.close()

Цей спосіб не зовсім безпечний. Якщо виникає виняток, коли ми виконуємо якусь операцію з файлом, код завершується, не закриваючи файл.

Більш безпечним способом є використання спроби… нарешті блокувати.

 try: f = open("test.txt", encoding = 'utf-8') # perform file operations finally: f.close()

Таким чином, ми гарантуємо, що файл належним чином закрито, навіть якщо створено виняток, який спричиняє зупинку потоку програми.

Найкращий спосіб закрити файл - це використання withоператора. Це гарантує, що файл буде закритий під час виходу із блоку усередині withоператора.

Нам не потрібно явно викликати close()метод. Це робиться внутрішньо.

 with open("test.txt", encoding = 'utf-8') as f: # perform file operations

Запис у файли на Python

Для того, щоб писати у файл на Python, нам потрібно відкрити його в режимі запису w, додавання aабо ексклюзивного створення x.

Нам слід бути обережними з wрежимом, оскільки він перезапише файл, якщо він уже існує. Завдяки цьому всі попередні дані стираються.

Writing a string or sequence of bytes (for binary files) is done using the write() method. This method returns the number of characters written to the file.

 with open("test.txt",'w',encoding = 'utf-8') as f: f.write("my first file") f.write("This file") f.write("contains three lines")

This program will create a new file named test.txt in the current directory if it does not exist. If it does exist, it is overwritten.

We must include the newline characters ourselves to distinguish the different lines.

Reading Files in Python

To read a file in Python, we must open the file in reading r mode.

There are various methods available for this purpose. We can use the read(size) method to read in the size number of data. If the size parameter is not specified, it reads and returns up to the end of the file.

We can read the text.txt file we wrote in the above section in the following way:

 >>> f = open("test.txt",'r',encoding = 'utf-8') >>> f.read(4) # read the first 4 data 'This' >>> f.read(4) # read the next 4 data ' is ' >>> f.read() # read in the rest till end of file 'my first fileThis filecontains three lines' >>> f.read() # further reading returns empty sting ''

We can see that the read() method returns a newline as ''. Once the end of the file is reached, we get an empty string on further reading.

We can change our current file cursor (position) using the seek() method. Similarly, the tell() method returns our current position (in number of bytes).

 >>> f.tell() # get the current file position 56 >>> f.seek(0) # bring file cursor to initial position 0 >>> print(f.read()) # read the entire file This is my first file This file contains three lines

We can read a file line-by-line using a for loop. This is both efficient and fast.

 >>> for line in f:… print(line, end = '')… This is my first file This file contains three lines

In this program, the lines in the file itself include a newline character . So, we use the end parameter of the print() function to avoid two newlines when printing.

Alternatively, we can use the readline() method to read individual lines of a file. This method reads a file till the newline, including the newline character.

 >>> f.readline() 'This is my first file' >>> f.readline() 'This file' >>> f.readline() 'contains three lines' >>> f.readline() ''

Lastly, the readlines() method returns a list of remaining lines of the entire file. All these reading methods return empty values when the end of file (EOF) is reached.

 >>> f.readlines() ('This is my first file', 'This file', 'contains three lines')

Python File Methods

There are various methods available with the file object. Some of them have been used in the above examples.

Here is the complete list of methods in text mode with a brief description:

Method Description
close() Closes an opened file. It has no effect if the file is already closed.
detach() Separates the underlying binary buffer from the TextIOBase and returns it.
fileno() Returns an integer number (file descriptor) of the file.
flush() Flushes the write buffer of the file stream.
isatty() Returns True if the file stream is interactive.
read(n) Reads at most n characters from the file. Reads till end of file if it is negative or None.
readable() Returns True if the file stream can be read from.
readline(n=-1) Reads and returns one line from the file. Reads in at most n bytes if specified.
readlines(n=-1) Reads and returns a list of lines from the file. Reads in at most n bytes/characters if specified.
seek(offset,from=SEEK_SET) Changes the file position to offset bytes, in reference to from (start, current, end).
seekable() Returns True if the file stream supports random access.
tell() Returns the current file location.
truncate(size=None) Resizes the file stream to size bytes. If size is not specified, resizes to current location.
writable() Returns True if the file stream can be written to.
write(s) Записує рядок s у файл і повертає кількість записаних символів.
лінії запису (рядки) Записує у файл список рядків.

Цікаві статті...