Python print file type

Python – Determine File Type

In this tutorial, we’ll try to understand how to determine the file type using Python with the help of some examples.

There are multiple ways to detect the type of a file using Python. For example –

  1. Get the file type using the file name and its extension using the os.path.splitext() function. For example, the file “cat.png” appears to be an image file since it has “.png” as its extension.
  2. Alternatively, you can determine the file based on the contents of the file as well by using the python-magic library.

Let’s look at both methods in detail.

Method 1- Using os.path.splitext() method

This is an inbuilt method in os library which splits the pathname into a (root, ext) pair such that root + ext == path . The extension, ext, is either empty or begins with a period and contains at most one period.

Basic Syntax:

Parameters: The only parameter is path which indicates the path of the file specified.

Читайте также:  Приклеенный заголовок

Let’s now look at the usage of this method with some worked out examples

Example 1 – Simple path

import os print(os.path.splitext("file1.txt"))

Here, we get the filename and the extension of the file. From the extension, we can say that the given file is a text file.

Example 2 – Path with No extension

What happens if the filename does not contain any extension?

import os print(os.path.splitext("file"))

As there is no extension in the path specified, we can only see the filename and can’t really determine the file type here.

Example 3 – Path containing an extension

Let’s look at another example of a filename with a confusing extension.

import os print(os.path.splitext("foo.bar.exe"))

We can say that the given file is an executable file (it has .exe as its extension). As the path contains an extension, then ext will be set to this extension, including the leading period. Note that previous periods will be ignored.

Example 4 – Path containing leading periods

import os print(os.path.splitext(".sdfasg")) print(os.path.splitext("/faaaoo/gves/. png"))

Here we can see that the leading periods of the last component of the path are considered to be part of the root.

A drawback of determining file type from its extension

In this method, we are trying to determine the file type just by looking at the path of the file. But if we think about it, we can see a case where the path of the file has an extension of one type, but the content in the file is of another type. A simple example can be, a file named “f1.jpg” can have the content inside which is of type HTML. So, for such cases, we cannot just determine the file type by using its name/path.

The solution can be to use the magic number associated with the file to determine the type of the file. A magic number is a fixed number that is used to identify a file. This approach gives you more freedom when naming files and does not require an extension. Magic numbers are useful for identifying files because files can occasionally have incorrect file extensions.

This is can be done using the python.magic library.

Method 2 – Using the python-magic library

You can use the magic.from_file() method available in the python-magic library to determine the type of a file based on its contents. It uses the magic number associated with the file to determine its type.

The following is the syntax –

Basic Syntax:

Parameters: The parameters are path that indicates the path of the file specified and mime(True/False) that attains the mime type of the file (optional).

For more information, refer this.

Let’s now look at the usage of the above method with an example.

Example – Determine file type

Let’s say we create a simple file with HTML markup inside but name the file with a “.jpg” extension. Look at the image below.

file with HTML content

The contents of this file are saved under the name “cats.jpg”. Now, let’s try to determine its type using the magic.from_file() method.

import magic print(magic.from_file("cats.png"))
HTML document, ASCII text, with CRLF line terminators

Here, we can see that, even though the file is a jpg file, the inside content is of type HTML, so the output of the program is an HTML file.

Summary

In this tutorial, we understood how to determine the file type using os.path.splitext method. Then, we understood the drawback of using this method and then tried to understand python-magic library which is better to use.

You might also be interested in –

Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.

Author

I’m an undergrad student at IIT Madras interested in exploring new technologies. I have worked on various projects related to Data science, Machine learning & Neural Networks, including image classification using Convolutional Neural Networks, Stock prediction using Recurrent Neural Networks, and many more machine learning model training. I write blog articles in which I would try to provide a complete guide on a particular topic and try to cover as many different examples as possible with all the edge cases to understand the topic better and have a complete glance over the topic. View all posts

Career Guides

  • Start Your Path
  • Data Scientist
  • Data Analyst
  • Data Engineer
  • Machine Learning Engineer
  • Statistician
  • Data Architect
  • Software Developer

Источник

Как работает функция print в Python

Обложка: Как работает функция print в Python

Функция print() в Python используется для вывода текстовой информации на экран или в консоль. Эта функция может принимать один или несколько аргументов. Одним из обязательных аргументов является строка или объект, который будет выведен.

Вы наверняка знакомы с этой функцией. С неё начинается любой урок по программированию на Python.

В данном случае функция выведет в консоль сообщение:

При этом обязательно использовать скобки, иначе возникнет синтаксическая ошибка. В Python 2 скобки можно было не указывать, но в Python 3 скобки необходимы. Всё потому, что в третьей версии print() — это функция, а не инструкция.

Убедимся, что перед нами действительно функция, и спросим Python:

Python ответит нам, что перед нами встроенная функция или метод.

builtin_function_or_method 

Аргументы print() в Python

Аргументы функции print() позволяют изменять способ форматирования сообщений и управлять стилем вывода.

Вот полный синтаксис функции, скрытый от наших глаз:

print(value, . sep=' ', end='\n', file=sys.stdout, flush=False) 

Аргументы функции здесь — это sep , end , file и flush :

  1. sep позволяет задать разделитель, который будет выводиться между элементами, переданными в функцию print(). По умолчанию разделителем является пробел, но с помощью sep пробел можно заменить на другой разделитель, к примеру, на запятую.
  2. end позволяет определять символ, который будет добавлен в конец сообщения после вывода. По умолчанию это символ перевода строки. Поменять его можно, к примеру, на точку с запятой.
  3. file позволяет перенаправить вывод текста в нужный вам файл. По умолчанию функция выводит текст в консоль, в которой вы и задаёте команды Python. Аргумент file полезен, если нужно сохранить вывод для дальнейшего использования.
  4. flush позволяет управлять буферизацией вывода. Если этот аргумент установлен в True, то вывод не будет буферизоваться и будет выводиться немедленно.

Рассмотрим эти аргументы чуть подробнее.

Аргумент sep в функции print() на Python

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

Попросим Python вывести на экран слова, не меняя при этом sep .

print('туториал', 'по', 'функции', 'print()') 

Убеждаемся, что sep по умолчанию — это пробел. На экране появится такое сообщение:

туториал по функции print() 

Теперь попробуем заменить дефолтный пробел в sep на что-то другое. Используем символы \n в качестве разделителя в аргументе sep . Они должны перенести каждый следующий элемент выдачи на новую строку.

print('туториал', 'по', 'функции', 'print()', sep='\n') 

Получается вот такой вывод функции:

туториал по функции print() 

Как и ожидалось, после каждого слова в выводе строка переносится, ведь разделителем мы назначили именно перенос строки. 🙂

Аргумент end в функции print() на Python

Аргумент end — это суть то же самое, что и sep . Разница только в том, что sep — это разделитесь между элементами вывода, а end — это разделитесь самих выводов разных функций print() , если их несколько.

По умолчанию end — это перенос строки. Его тоже можно заменить на любое другое удобное значение.

Вот, как выглядит стандартный вывод функций print() , если не менять аргумент end .

print('Брюки - это') print('одежда, которая надевается на нижнюю часть тела.') 
Брюки - это одежда, которая надевается на нижнюю часть тела. 

Попробуем заменить перенос строки в аргументе end на обычный пробел.

print('Брюки - это', end=' ') print('одежда, которая надевается на нижнюю часть тела.') 

Вывод с обычным пробелом вместо переноса строки:

Брюки - это одежда, которая надевается на нижнюю часть тела. 

Аргумент file в функции print() на Python

Аргумент file позволяет записывать данные вывода в файлы с расширением txt или csv.

По умолчанию значение аргумента file указано как sys.stdout . Это — вывод значений непосредственно в консоль Python.

Допустим, нам нужно, чтобы по завершении программа записала вывод в файлик print.txt. Для этого напишем простую программу, которая:

file = open('print.txt','a+') #открываем файл def value(items): for item in items: print(item, file=file) #вызываем функцию print, вывод которой должен записаться в файл file.close() # закрываем файл value([1,2,3,4,5,6,7,8,9,10]) 

Результатом выполнения этого кода станет появление файла print.txt. Внутри него должно оказаться:

Аргумент flush в функции print() на Python

Аргумент flush в функции print() в Python позволяет управлять выводом сообщений без задержек.

Дело в том, что по умолчанию программа будет записывать данные вывода из print() сперва в буфер обмена, а уже потом выводить данные в консоль или в файл.

По умолчанию аргумент flush установлен в значении False .

Когда значение аргумента flush установлено в True , Python выводит сообщение, не дожидаясь буферизации вывода. Это полезно, когда нужно мгновенно показать вывод в консоли или в файле.

with open('output.txt', 'w') as f: print('Hello, world!', file=f, flush=True) 

В этом примере мы записали вывод Hello, world! в файл output.txt без буферизации, установив значение аргумента flush как True .

Однако с этим аргументом нужно быть осторожным:

  1. Если возникнет ошибка в выполнении программы, а аргумент flush установлен как True, результат вывода может быть утерян. Он не сохранится в буфере из-за значения True и не отобразится в консоли или в файле из-за ошибки.
  2. Использование flush=True при работе с несколькими потоками может привести к тому, что разные потоки будут пытаться выводить данные в поток вывода одновременно. Это приведет к ошибкам.

Использование flush=True без должной осторожности может создать проблемы в работе программы и усложнить отладку. Если нет необходимости в ручной записи данных в поток вывода, лучше не использовать этот параметр.

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

Источник

Оцените статью