Introduction

This article will teach you to remove the file extension from the filename using python. After reading this you should be able to deal with files while coding. We will use os and pathlib libraries in this article.

How to remove file extension from filename using python

For this, we'll use os.path.splitext(path). In truth, os.path.splitext(path) splits the pathname path into a pair (root, ext) such that root + ext == path, and the extension, ext, is either empty or starts with a period and has no more than one period. If there is no extension in the path, ext will be:

>>> splitext('bar') ('bar', '')

If the path contains an extension, ext will be set to this extension, including the leading period. Note that previous periods will be ignored:

>>> >>> splitext('foo.bar.exe')
('foo.bar', '.exe')
>>> splitext('/foo/bar.exe')
('/foo/bar', '.exe')

The leading periods of the path's last component are considered part of the root:

>>> >>> splitext('.cshrc')
('.cshrc', '')
>>> splitext('/foo/....jpg')
('/foo/....jpg', '')

We may also use pathlib.Path() to accomplish this. This module contains classes representing filesystem paths and providing semantics for various operating systems. Pure paths, which allow purely computational operations without I/O, and concrete paths, which inherit from pure pathways but also provide I/O operations, are the two path classes.

Solution 1

import os
print os.path.splitext('/home/user/somefile.txt')[0]+'.jpg'  # /home/user/somefile.jpg os.path.splitext('/home/user/somefile.txt')  # returns ('/home/user/somefile', '.txt')

Solution 2 Now, let’s move to another solution!

>>> from pathlib import Path
>>> filename = Path('/some/path/somefile.txt')
>>> filename_wo_ext = filename.with_suffix('')
>>> filename_replace_ext = filename.with_suffix('.jpg')
>>> print(filename) /some/path/somefile.ext
>>> print(filename_wo_ext) /some/path/somefile
>>> print(filename_replace_ext) /some/path/somefile.jpg

In general

Using python, we should use os or pathlib to remove the file extension from the filename.

Conclusion

The most straightforward methods to remove the file extension from the filename are using os or pathlib. In fact, both methods are working well if the file contains dots in it's name. Also, Os and Pathlib libraries play a vital role in dealing with files details.

Logo

Python社区为您提供最前沿的新闻资讯和知识内容

更多推荐