Hướng dẫn dùng file type python
I have a folder full of files and they don't have an extension. How can I check file types? I want to check the file type and change the filename accordingly. Let's assume a function
How do I do this? martineau 115k25 gold badges160 silver badges283 bronze badges asked Jun 7, 2012 at 18:06 9 There are Python libraries that can recognize files based on their content (usually a header / magic number) and that don't rely on the file name or extension. If you're addressing many different file types, you can use There are also libraries for more specialized file types. For example, the Python standard library has the If you need dependency-free (pure Python) file type checking, see phoenix 6,3884 gold badges36 silver badges44 bronze badges answered Jun 7, 2012 at 18:43 Chris JohnsonChris Johnson 19.5k5 gold badges77 silver badges77 bronze badges 3 The Python Magic library provides the functionality you need. You can install the library with
The Python code in this case is calling to libmagic beneath the hood, which is the same library used by the *NIX answered Jun 26, 2014 at 14:51 RichardRichard 51.6k30 gold badges168 silver badges243 bronze badges 3 On unix and linux there is the From the man page:
You would need to run the edit: Ignore my answer. Use Chris Johnson's answer instead. answered Jun 7, 2012 at 18:12 Steven RumbalskiSteven Rumbalski 43k8 gold badges85 silver badges117 bronze badges 3 In the case of images, you can use the
Python 2 imghdr doc phoenix 6,3884 gold badges36 silver badges44 bronze badges answered Oct 7, 2014 at 16:00 Lewis DiamondLewis Diamond 21.1k2 gold badges21 silver badges30 bronze badges
As Steven pointed out, answered Jun 7, 2012 at 18:25 xvatarxvatar 3,11915 silver badges19 bronze badges 3 You can also install the official It's available on PyPI as file-magic and on Debian as python-magic. For me this library is the best to use since it's available on PyPI and on Debian (and probably other distributions), making the process of deploying your software easier. I've blogged about how to use it, also. answered Aug 5, 2016 at 0:43 With newer subprocess library, you can now use the following code (*nix only solution):
answered Jun 6, 2014 at 3:14 bernieyberniey 2,6521 gold badge16 silver badges8 bronze badges 2 also you can use this code (pure python by 3 byte of header file):
answered Jul 6, 2019 at 10:36 evergreenevergreen 7,1612 gold badges15 silver badges25 bronze badges 2 Only works for Linux but Using the "sh" python module you can simply call any shell command https://pypi.org/project/sh/ pip install sh
Output: /root/file: ASCII text answered Feb 2, 2019 at 18:45 LelouchLelouch 4696 silver badges6 bronze badges This code list all files of a given extension in a given folder recursively
https://gist.github.com/izmcm/6a5d6fa8d4ec65fd9851a1c06c8946ac answered Aug 30, 2021 at 21:28 0 |