如何从Python中的路径获取没有扩展名的文件名?

时间:2022-09-01 22:12:32

How to get the filename without the extension from a path in Python?

如何从Python中的路径获取没有扩展名的文件名?

I found out a method called os.path.basename to get the filename with extension. But even when I import os, I am not able to call it path.basename. Is it possible to call it as directly as basename?

我找到了一个方法,叫做os。path。获得扩展名的文件名。但是即使我导入os,我也不能称之为path.basename。可以直接称它为basename吗?

18 个解决方案

#1


780  

Getting the name of the file without the extension :

获取没有扩展名的文件名称:

import os
print(os.path.splitext("path_to_file")[0])

As for your import problem, you solve it this way :

关于你的进口问题,你是这样解决的:

from os.path import basename

# now you can call it directly with basename
print(basename("/a/b/c.txt"))

#2


265  

Just roll it:

您可以:

>>> import os
>>> base=os.path.basename('/root/dir/sub/file.ext')
>>> base
'file.ext'
>>> os.path.splitext(base)
('file', '.ext')
>>> os.path.splitext(base)[0]
'file'

#3


134  

>>> print os.path.splitext(os.path.basename("hemanth.txt"))[0]
hemanth

#4


18  

For completeness sake, here is the pathlib solution for python 3.2+:

为了完整性起见,这里是python 3.2+的pathlib解决方案:

from pathlib import Path

print(Path(your_path).resolve().stem)

#5


16  

If you want to keep the path to the file and just remove the extension

如果您想保留文件的路径,只需删除扩展名

>>> file = '/root/dir/sub.exten/file.data.1.2.dat'
>>> print ('.').join(file.split('.')[:-1])
/root/dir/sub.exten/file.data.1.2

#6


15  

A readable version, using Pathlib in Python 3.4+

一个可读的版本,使用Python 3.4+中的Pathlib

from pathlib import Path

Path('/root/dir/sub/file.ext').stem

Will print :

将打印:

file

文件

If the path can be a symbolic link, then add resolve()

如果路径可以是一个符号链接,那么添加resolve()

Path('/root/dir/sub/file.ext').resolve().stem

#7


9  

os.path.splitext() won't work if there are multiple dots in the extension.

如果扩展中有多个点,那么splitext()将不起作用。

For example, images.tar.gz

例如,images.tar.gz

>>> import os
>>> file_path = '/home/dc/images.tar.gz'
>>> file_name = os.path.basename(file_path)
>>> print os.path.splitext(file_name)[0]
images.tar

You can just find the index of the first dot in the basename and then slice the basename to get just the filename without extension.

您可以在basename中找到第一个点的索引,然后对basename进行切片,以获得没有扩展的文件名。

>>> import os
>>> file_path = '/home/dc/images.tar.gz'
>>> file_name = os.path.basename(file_path)
>>> index_of_dot = file_name.index('.')
>>> file_name_without_extension = file_name[:index_of_dot]
>>> print file_name_without_extension
images

#8


8  

But even when I import os, I am not able to call it path.basename. Is it possible to call it as directly as basename?

但是即使我导入os,我也不能称之为path.basename。可以直接称它为basename吗?

import os, and then use os.path.basename

导入os,然后使用os.path.basename

importing os doesn't mean you can use os.foo without referring to os.

导入os并不意味着您可以使用os。foo没有指向os。

#9


7  

@IceAdor's refers to rsplit in a comment to @user2902201's solution. rsplit is the simplest solution that supports multiple periods.

@IceAdor指的是对@user2902201解决方案的评论。rsplit是支持多个周期的最简单的解决方案。

Here it is spelt out:

这里的拼写是:

file = 'my.report.txt'
print file.rsplit('.', 1)[0]

my.report

my.report

#10


4  

import os

进口操作系统

filename = C:\\Users\\Public\\Videos\\Sample Videos\\wildlife.wmv

This returns the filename without the extension(C:\Users\Public\Videos\Sample Videos\wildlife)

这将返回没有扩展名的文件名(C:\用户\公共视频\示例视频\野生动物)

temp = os.path.splitext(filename)[0]  

Now you can get just the filename from the temp with

现在您可以从临时文件中获得文件名

os.path.basename(temp)   #this returns just the filename (wildlife)

#11


3  

Thought I would throw in a variation to the use of the os.path.splitext without the need to use array indexing.

我认为我将会改变对轨道的使用。不需要使用数组索引的splitext。

The function always returns a (root, ext) pair so it is safe to use:

该函数始终返回一个(root, ext)对,因此可以安全地使用:

root, ext = os.path.splitext(path)

根,ext = os.path.splitext(路径)

Example:

例子:

>>> import os
>>> path = 'my_text_file.txt'
>>> root, ext = os.path.splitext(path)
>>> root
'my_text_file'
>>> ext
'.txt'

#12


2  

On Windows system I used drivername prefix as well, like:

在Windows系统上,我也使用了驱动程序名前缀,比如:

>>> s = 'c:\\temp\\akarmi.txt'
>>> print(os.path.splitext(s)[0])
c:\temp\akarmi

So because I do not need drive letter or directory name, I use:

因此,因为我不需要驱动器名或目录名,所以我使用:

>>> print(os.path.splitext(os.path.basename(s))[0])
akarmi

#13


2  

import os
path = "a/b/c/abc.txt"
print os.path.splitext(os.path.basename(path))[0]

#14


2  

A multiple extension aware procedure. Works for str and unicode paths. Works in Python 2 and 3.

多扩展识别过程。适用于str和unicode路径。适用于Python 2和3。

import os

def file_base_name(file_name):
    if '.' in file_name:
        separator_index = file_name.index('.')
        base_name = file_name[:separator_index]
        return base_name
    else:
        return file_name

def path_base_name(path):
    file_name = os.path.basename(path)
    return file_base_name(file_name)

Behavior:

行为:

>>> path_base_name('file')
'file'
>>> path_base_name(u'file')
u'file'
>>> path_base_name('file.txt')
'file'
>>> path_base_name(u'file.txt')
u'file'
>>> path_base_name('file.tar.gz')
'file'
>>> path_base_name('file.a.b.c.d.e.f.g')
'file'
>>> path_base_name('relative/path/file.ext')
'file'
>>> path_base_name('/absolute/path/file.ext')
'file'
>>> path_base_name('Relative\\Windows\\Path\\file.txt')
'file'
>>> path_base_name('C:\\Absolute\\Windows\\Path\\file.txt')
'file'
>>> path_base_name('/path with spaces/file.ext')
'file'
>>> path_base_name('C:\\Windows Path With Spaces\\file.txt')
'file'
>>> path_base_name('some/path/file name with spaces.tar.gz.zip.rar.7z')
'file name with spaces'

#15


1  

We could do some simple split / pop magic as seen here (https://*.com/a/424006/1250044), to extract the filename (respecting the windows and POSIX differences).

我们可以在这里做一些简单的拆分/流行魔术(https://*.com/a/424006/1250044),以提取文件名(关于窗口和POSIX差异)。

def getFileNameWithoutExtension(path):
  return path.split('\\').pop().split('/').pop().rsplit('.', 1)[0]

getFileNameWithoutExtension('/path/to/file-0.0.1.ext')
# => file-0.0.1

getFileNameWithoutExtension('\\path\\to\\file-0.0.1.ext')
# => file-0.0.1

#16


0  

For convenience, a simple function wrapping the two methods from os.path :

为了方便,一个简单的函数将这两种方法从os包装起来。路径:

def filename(path):
  """Return file name without extension from path.

  See https://docs.python.org/3/library/os.path.html
  """
  import os.path
  b = os.path.split(path)[1]  # path, *filename*
  f = os.path.splitext(b)[0]  # *file*, ext
  #print(path, b, f)
  return f

Tested with Python 3.5.

与Python 3.5测试。

#17


0  

import os
list = []
def getFileName( path ):
for file in os.listdir(path):
    #print file
    try:
        base=os.path.basename(file)
        splitbase=os.path.splitext(base)
        ext = os.path.splitext(base)[1]
        if(ext):
            list.append(base)
        else:
            newpath = path+"/"+file
            #print path
            getFileName(newpath)
    except:
        pass
return list

getFileName("/home/weexcel-java3/Desktop/backup")
print list

#18


0  

the easiest way to resolve this is to

解决这个问题最简单的方法是

import ntpath 
print('Base name is ',ntpath.basename('/path/to/the/file/'))

this saves you time and computation cost.

这节省了您的时间和计算成本。

#1


780  

Getting the name of the file without the extension :

获取没有扩展名的文件名称:

import os
print(os.path.splitext("path_to_file")[0])

As for your import problem, you solve it this way :

关于你的进口问题,你是这样解决的:

from os.path import basename

# now you can call it directly with basename
print(basename("/a/b/c.txt"))

#2


265  

Just roll it:

您可以:

>>> import os
>>> base=os.path.basename('/root/dir/sub/file.ext')
>>> base
'file.ext'
>>> os.path.splitext(base)
('file', '.ext')
>>> os.path.splitext(base)[0]
'file'

#3


134  

>>> print os.path.splitext(os.path.basename("hemanth.txt"))[0]
hemanth

#4


18  

For completeness sake, here is the pathlib solution for python 3.2+:

为了完整性起见,这里是python 3.2+的pathlib解决方案:

from pathlib import Path

print(Path(your_path).resolve().stem)

#5


16  

If you want to keep the path to the file and just remove the extension

如果您想保留文件的路径,只需删除扩展名

>>> file = '/root/dir/sub.exten/file.data.1.2.dat'
>>> print ('.').join(file.split('.')[:-1])
/root/dir/sub.exten/file.data.1.2

#6


15  

A readable version, using Pathlib in Python 3.4+

一个可读的版本,使用Python 3.4+中的Pathlib

from pathlib import Path

Path('/root/dir/sub/file.ext').stem

Will print :

将打印:

file

文件

If the path can be a symbolic link, then add resolve()

如果路径可以是一个符号链接,那么添加resolve()

Path('/root/dir/sub/file.ext').resolve().stem

#7


9  

os.path.splitext() won't work if there are multiple dots in the extension.

如果扩展中有多个点,那么splitext()将不起作用。

For example, images.tar.gz

例如,images.tar.gz

>>> import os
>>> file_path = '/home/dc/images.tar.gz'
>>> file_name = os.path.basename(file_path)
>>> print os.path.splitext(file_name)[0]
images.tar

You can just find the index of the first dot in the basename and then slice the basename to get just the filename without extension.

您可以在basename中找到第一个点的索引,然后对basename进行切片,以获得没有扩展的文件名。

>>> import os
>>> file_path = '/home/dc/images.tar.gz'
>>> file_name = os.path.basename(file_path)
>>> index_of_dot = file_name.index('.')
>>> file_name_without_extension = file_name[:index_of_dot]
>>> print file_name_without_extension
images

#8


8  

But even when I import os, I am not able to call it path.basename. Is it possible to call it as directly as basename?

但是即使我导入os,我也不能称之为path.basename。可以直接称它为basename吗?

import os, and then use os.path.basename

导入os,然后使用os.path.basename

importing os doesn't mean you can use os.foo without referring to os.

导入os并不意味着您可以使用os。foo没有指向os。

#9


7  

@IceAdor's refers to rsplit in a comment to @user2902201's solution. rsplit is the simplest solution that supports multiple periods.

@IceAdor指的是对@user2902201解决方案的评论。rsplit是支持多个周期的最简单的解决方案。

Here it is spelt out:

这里的拼写是:

file = 'my.report.txt'
print file.rsplit('.', 1)[0]

my.report

my.report

#10


4  

import os

进口操作系统

filename = C:\\Users\\Public\\Videos\\Sample Videos\\wildlife.wmv

This returns the filename without the extension(C:\Users\Public\Videos\Sample Videos\wildlife)

这将返回没有扩展名的文件名(C:\用户\公共视频\示例视频\野生动物)

temp = os.path.splitext(filename)[0]  

Now you can get just the filename from the temp with

现在您可以从临时文件中获得文件名

os.path.basename(temp)   #this returns just the filename (wildlife)

#11


3  

Thought I would throw in a variation to the use of the os.path.splitext without the need to use array indexing.

我认为我将会改变对轨道的使用。不需要使用数组索引的splitext。

The function always returns a (root, ext) pair so it is safe to use:

该函数始终返回一个(root, ext)对,因此可以安全地使用:

root, ext = os.path.splitext(path)

根,ext = os.path.splitext(路径)

Example:

例子:

>>> import os
>>> path = 'my_text_file.txt'
>>> root, ext = os.path.splitext(path)
>>> root
'my_text_file'
>>> ext
'.txt'

#12


2  

On Windows system I used drivername prefix as well, like:

在Windows系统上,我也使用了驱动程序名前缀,比如:

>>> s = 'c:\\temp\\akarmi.txt'
>>> print(os.path.splitext(s)[0])
c:\temp\akarmi

So because I do not need drive letter or directory name, I use:

因此,因为我不需要驱动器名或目录名,所以我使用:

>>> print(os.path.splitext(os.path.basename(s))[0])
akarmi

#13


2  

import os
path = "a/b/c/abc.txt"
print os.path.splitext(os.path.basename(path))[0]

#14


2  

A multiple extension aware procedure. Works for str and unicode paths. Works in Python 2 and 3.

多扩展识别过程。适用于str和unicode路径。适用于Python 2和3。

import os

def file_base_name(file_name):
    if '.' in file_name:
        separator_index = file_name.index('.')
        base_name = file_name[:separator_index]
        return base_name
    else:
        return file_name

def path_base_name(path):
    file_name = os.path.basename(path)
    return file_base_name(file_name)

Behavior:

行为:

>>> path_base_name('file')
'file'
>>> path_base_name(u'file')
u'file'
>>> path_base_name('file.txt')
'file'
>>> path_base_name(u'file.txt')
u'file'
>>> path_base_name('file.tar.gz')
'file'
>>> path_base_name('file.a.b.c.d.e.f.g')
'file'
>>> path_base_name('relative/path/file.ext')
'file'
>>> path_base_name('/absolute/path/file.ext')
'file'
>>> path_base_name('Relative\\Windows\\Path\\file.txt')
'file'
>>> path_base_name('C:\\Absolute\\Windows\\Path\\file.txt')
'file'
>>> path_base_name('/path with spaces/file.ext')
'file'
>>> path_base_name('C:\\Windows Path With Spaces\\file.txt')
'file'
>>> path_base_name('some/path/file name with spaces.tar.gz.zip.rar.7z')
'file name with spaces'

#15


1  

We could do some simple split / pop magic as seen here (https://*.com/a/424006/1250044), to extract the filename (respecting the windows and POSIX differences).

我们可以在这里做一些简单的拆分/流行魔术(https://*.com/a/424006/1250044),以提取文件名(关于窗口和POSIX差异)。

def getFileNameWithoutExtension(path):
  return path.split('\\').pop().split('/').pop().rsplit('.', 1)[0]

getFileNameWithoutExtension('/path/to/file-0.0.1.ext')
# => file-0.0.1

getFileNameWithoutExtension('\\path\\to\\file-0.0.1.ext')
# => file-0.0.1

#16


0  

For convenience, a simple function wrapping the two methods from os.path :

为了方便,一个简单的函数将这两种方法从os包装起来。路径:

def filename(path):
  """Return file name without extension from path.

  See https://docs.python.org/3/library/os.path.html
  """
  import os.path
  b = os.path.split(path)[1]  # path, *filename*
  f = os.path.splitext(b)[0]  # *file*, ext
  #print(path, b, f)
  return f

Tested with Python 3.5.

与Python 3.5测试。

#17


0  

import os
list = []
def getFileName( path ):
for file in os.listdir(path):
    #print file
    try:
        base=os.path.basename(file)
        splitbase=os.path.splitext(base)
        ext = os.path.splitext(base)[1]
        if(ext):
            list.append(base)
        else:
            newpath = path+"/"+file
            #print path
            getFileName(newpath)
    except:
        pass
return list

getFileName("/home/weexcel-java3/Desktop/backup")
print list

#18


0  

the easiest way to resolve this is to

解决这个问题最简单的方法是

import ntpath 
print('Base name is ',ntpath.basename('/path/to/the/file/'))

this saves you time and computation cost.

这节省了您的时间和计算成本。