Home python Definition of file expansion in python

Definition of file expansion in python

Author

Date

Category

How in Python make the most correctly check on the file extension? Let’s say, the file name falls to me and I want to check if it is extension .py or not.


Answer 1, Authority 100%

Use os.path.splitext :

& gt; & gt; & gt; Import OS.
& gt; & gt; & gt; FileName, File_Extension = OS.path.splitext ('/ Path / To / SomeFile.ext')
& gt; & gt; & gt; FileName.
'/ Path / To / SomeFile'
& gt; & gt; & gt; File_Extension.
'.EXT'

Answer 2, Authority 86%

I like the file name and I want to check if it is extension .py

filename.endswith ('. Py') The method returns whether filename (string containing the file name) on '. PY' .

If the path is asked as Pathlib.path Object, then .suffix Returns the file extension :

& gt; & gt; & gt; From Pathlib Import Path
& gt; & gt; & gt; Path ('My / Library / setup.py'). Suffix == '.py'
True.

If you need to find all extensions, you can .suffixes Attribute Use:

& gt; & gt; & gt; Path ('My / Library.tar.gz'). Suffixes
['.tar', '.gz']

“Maximum correct” use the simplest readable code that works.

Essential difference is the case when the name of the directory is set to the layer at the end, then Pathlib.path different from os.path.splitext () or str.endswith () :

& gt; & gt; & gt; Import OS.
& gt; & gt; & gt; OS.path.splitext ('Pypy / RLIB / RSRE__GEN.py /') [1] == '.py'
FALSE # NOT TRUE !!!
& gt; & gt; & gt; 'pypy / rlib / rsre__gen.py /'. ENDSWITH ('. PY')
FALSE # NOT TRUE !!!
& gt; & gt; & gt; PATH ('Pypy / RLIB / RSRE__GEN.py /'). Suffix == '.py'
True.

Answer 3

extension = '/path/to/somefile.ext'.split('.') [1]
Print (Extension)

Answer 4

Faster everything without any arrays and suffixes:

Ext = somefilename [somefilename.rfind (".") + 1:]

Answer 5

# is too manually, but this is what immediately comes to mind
Import OS.
T = INPUT ('Enter the path to the folder:')
DOCS, MUSIC, OTHER = [], [], []
for root, dirs, files in os.walk (t):
  FOR FILE IN FILES:
    If File [-4 ::] == '. Doc' or File [-5 ::] == '. docx':
      docs.join (os.path.join (File))
    ELIF file [-4 ::] == '. Mp3' or File [-4 ::] == '. WAV':
      Music.Join (OS.path.join (File))
# Here insert any formats
    ELSE:
      Other.append (os.path.join (File))
Print ('\ NDI channels: \ n')
For el in docs:
  Print (EL)
Print ('\ Nmuska: \ n')
For El In Music:
  Print (EL)
Print ('\ New: \ n')
For El In Other:
  Print (EL)

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions