Opening file with python

Файлы в python, ввод-вывод

Эта статья посвящена работе с файлами (вводу/выводу) в Python: открытие, чтение, запись, закрытие и другие операции.

Файлы Python

Файл — это всего лишь набор данных, сохраненный в виде последовательности битов на компьютере. Информация хранится в куче данных (структура данных) и имеет название «имя файла» (filename).

В Python существует два типа файлов:

Текстовые файлы

Это файлы с человекочитаемым содержимым. В них хранятся последовательности символов, которые понимает человек. Блокнот и другие стандартные редакторы умеют читать и редактировать этот тип файлов.

Текст может храниться в двух форматах: ( .txt ) — простой текст и ( .rtf ) — «формат обогащенного текста».

Бинарные файлы

В бинарных файлах данные отображаются в закодированной форме (с использованием только нулей (0) и единиц (1) вместо простых символов). В большинстве случаев это просто последовательности битов.

Они хранятся в формате .bin .

Любую операцию с файлом можно разбить на три крупных этапа:

Открытие файла

Метод open()

В Python есть встроенная функция open() . С ее помощью можно открыть любой файл на компьютере. Технически Python создает на его основе объект.

f = open(file_name, access_mode) 
  • file_name = имя открываемого файла
  • access_mode = режим открытия файла. Он может быть: для чтения, записи и т. д. По умолчанию используется режим чтения ( r ), если другое не указано. Далее полный список режимов открытия файла

Пример

Создадим текстовый файл example.txt и сохраним его в рабочей директории.

Текстовый файл пример

Следующий код используется для его открытия.

f = open('example.txt','r') # открыть файл из рабочей директории в режиме чтения fp = open('C:/xyz.txt','r') # открыть файл из любого каталога 

В этом примере f — переменная-указатель на файл example.txt .

Следующий код используется для вывода содержимого файла и информации о нем.

>>> print(*f) # выводим содержимое файла This is a text file. >>> print(f) # выводим объект _io.TextIOWrapper name='example.txt' mode='r' encoding='cp1252'> 

Стоит обратить внимание, что в Windows стандартной кодировкой является cp1252 , а в Linux — utf-08 .

Закрытие файла

Метод close()

После открытия файла в Python его нужно закрыть. Таким образом освобождаются ресурсы и убирается мусор. Python автоматически закрывает файл, когда объект присваивается другому файлу.

Существуют следующие способы:

Проще всего после открытия файла закрыть его, используя метод close() .

f = open('example.txt','r') # работа с файлом f.close() 

После закрытия этот файл нельзя будет использовать до тех пор, пока заново его не открыть.

Также можно написать try/finally , которое гарантирует, что если после открытия файла операции с ним приводят к исключениям, он закроется автоматически.

Без него программа завершается некорректно.

Вот как сделать это исключение:

f = open('example.txt','r') try: # работа с файлом finally: f.close() 

Файл нужно открыть до инструкции try , потому что если инструкция open сама по себе вызовет ошибку, то файл не будет открываться для последующего закрытия.

Этот метод гарантирует, что если операции над файлом вызовут исключения, то он закроется до того как программа остановится.

Инструкция with

Еще один подход — использовать инструкцию with , которая упрощает обработку исключений с помощью инкапсуляции начальных операций, а также задач по закрытию и очистке.

В таком случае инструкция close не нужна, потому что with автоматически закроет файл.

Вот как это реализовать в коде.

with open('example.txt') as f: # работа с файлом 

Чтение и запись файлов в Python

В Python файлы можно читать или записывать информацию в них с помощью соответствующих режимов.

Функция read()

Функция read() используется для чтения содержимого файла после открытия его в режиме чтения ( r ).

  • file = объект файла
  • size = количество символов, которые нужно прочитать. Если не указать, то файл прочитается целиком.
>>> f = open('example.txt','r') >>> f.read(7) # чтение 7 символов из example.txt 'This is ' 

Интерпретатор прочитал 7 символов файла и если снова использовать функцию read() , то чтение начнется с 8-го символа.

>>> f.read(7) # чтение следующих 7 символов ' a text' 

Функция readline()

Функция readline() используется для построчного чтения содержимого файла. Она используется для крупных файлов. С ее помощью можно получать доступ к любой строке в любой момент.

Создадим файл test.txt с нескольким строками:

This is line1. This is line2. This is line3. 

Посмотрим, как функция readline() работает в test.txt .

>>> x = open('test.txt','r') >>> x.readline() # прочитать первую строку This is line1. >>> x.readline(2) # прочитать вторую строку This is line2. >>> x.readlines() # прочитать все строки ['This is line1.','This is line2.','This is line3.'] 

Обратите внимание, как в последнем случае строки отделены друг от друга.

Функция write()

Функция write() используется для записи в файлы Python, открытые в режиме записи.

Если пытаться открыть файл, которого не существует, в этом режиме, тогда будет создан новый.

Предположим, файла xyz.txt не существует. Он будет создан при попытке открыть его в режиме чтения.

>>> f = open('xyz.txt','w') # открытие в режиме записи >>> f.write('Hello \n World') # запись Hello World в файл Hello World >>> f.close() # закрытие файла 

Переименование файлов в Python

Функция rename()

Функция rename() используется для переименовывания файлов в Python. Для ее использования сперва нужно импортировать модуль os.

import os os.rename(src,dest) 
>>> import os >>> # переименование xyz.txt в abc.txt >>> os.rename("xyz.txt","abc.txt") 

Текущая позиция в файлах Python

В Python возможно узнать текущую позицию в файле с помощью функции tell() . Таким же образом можно изменить текущую позицию командой seek() .

>>> f = open('example.txt') # example.txt, который мы создали ранее >>> f.read(4) # давайте сначала перейдем к 4-й позиции This >>> f.tell() # возвращает текущую позицию 4 >>> f.seek(0,0) # вернем положение на 0 снова 

Методы файла в Python

file.close() закрывает открытый файл
file.fileno() возвращает целочисленный дескриптор файла
file.flush() очищает внутренний буфер
file.isatty() возвращает True, если файл привязан к терминалу
file.next() возвращает следующую строку файла
file.read(n) чтение первых n символов файла
file.readline() читает одну строчку строки или файла
file.readlines() читает и возвращает список всех строк в файле
file.seek(offset[,whene]) устанавливает текущую позицию в файле
file.seekable() проверяет, поддерживает ли файл случайный доступ. Возвращает True , если да
file.tell() возвращает текущую позицию в файле
file.truncate(n) уменьшает размер файл. Если n указала, то файл обрезается до n байт, если нет — до текущей позиции
file.write(str) добавляет строку str в файл
file.writelines(sequence) добавляет последовательность строк в файл

Источник

How to Open Files in Python

Python gives us file handling methods within its standard library. This is really convenient as a developer since you do not really need to import any more modules for handling files.

The key methods provided to us by the Python for file handling are open() , close() , write() , read() , seek() and append() .

Let’s go over the open() method that allows us to open files in Python in different modes.

Open Files in Python

To open a file, all we need is the directory path that the file is located in. If it’s located in the same directory then including just the complete filename will suffice.

I’ve created a file with some sample text in it which we’ll use as a sample to learn the open file method.

Python Open File Sample File Contents

1. Opening a file using the open() method

To open the OpenFile.txt and read the text contents of the file, let’s use the open() and the read() methods.

file = open('OpenFile.txt') print(file.read()) file.close()

The read() method will read the entire contents of the file.

Python Open File Output

By default, the open() method opens a file in read-only mode. To write to a file, we will need to specify that the file has to be opened in write mode.

2. Different Modes For open() Method

Let’s try to write to the file with the default mode on.

file = open('OpenFile.txt') print(file.read()) file.write("testing write") file.close()

We’ll keep the read operation as it is so we can see where the code stops.

File Write Not Permitted Read Only Mode

So what are modes, and how do we add them? Below is a list of modes when using the open() method.

  • r: Read-Only mode.
  • r+: Read and write mode. Will not create a new file and open will fail if the file does not exist
  • rb: Read-only binary mode to read images, videos, etc.
  • w: Write-only mode. Overwrites existing file content. This will create a new file if the specified filename does not exist.
  • w+: Read and write mode.
  • wb: Binary write-only mode for writing to media files.
  • wb+: Binary read and write mode.
  • a: Append mode. Does not overwrite existing content
  • a+: Append and read mode. It will create a new file if the filename does not exist.
  • ab: Append binary mode for images, videos, etc.
  • ab+: Append and read binary mode.

3. Opening Files in Write Mode in Python

There are multiple ways you can open a file in write mode in Python. Depending on how you want the file handling methods to write to a file, you can use one of the below modes.

file = open('OpenFile.txt', 'w') print(file.read()) file.close()

By adding the ‘w’ while opening the file in the first line, we specify that the file should be opened in write mode. But this operation would fail too because the file is write-only and won’t allow us to use the read() method.

Write Only Mode File Not Readable

file = open('OpenFile.txt', 'w') file.write('New content\n') file.close()

The above code will completely clear all the contents of the text file and instead just say “New content”.

If you do not want to overwrite the file, you can use the a+ or r+ modes.

The r+ mode will write any content passed to the write() method.

file = open('OpenFile.txt', 'r+') print(file.read()) file.write('r+ method, adds a line\n') file.close()

The a or a+ mode will perform the same action as the r+ mode with one main difference.

In the case of the r+ method, a new file will not be created if the filename specified does not exist. But with a+ mode, a new file will be created if the specified file is not available.

4. Opening Files Using the with clause

When reading files with the open() method, you always need to make sure that the close() method is called to avoid memory leaks. As a developer, you could miss out on adding the close() method causing your program to leak file memory due to the file being open.

With smaller files, there isn’t a very noticeable effect on the system resources but it would show up when working with larger files.

with open('OpenFile.txt', 'r+') as file: print(file.read())

Python Open File Output

In the above example, the output would be the same as the ones we saw in the beginning, but we don’t have to close the file.

A with block acquires a lock as soon as it’s executed and releases the lock once the block ends.

You can also run other methods on the data while staying within the with code block. I’ve edited the OpenFile.txt, in this case, and added some more text for better understanding.

with open('OpenFile.txt', 'r+') as file: lines = file.readlines() for line in lines: print(line.split())

With Command Open File Python

The with statement does the memory handling for us as long as we continue to work within its scope. This is yet another but the better way to work with files in Python.

Conclusion

You should now have a grasp on how to open a file in Python and handle the different modes for opening a file with the open() method. We’ll cover further file handling methods in upcoming tutorials.

Источник

Читайте также:  Php сделать отрицательное число
Оцените статью