Jak pobrać nazwę pliku bez rozszerzenia ze ścieżki w Pythonie?

Jak pobrać nazwę pliku bez rozszerzenia ze ścieżki w Pythonie?

Znalazłem metodę os.path.basename aby uzyskać nazwę pliku z rozszerzeniem. Ale nawet gdy importuję system operacyjny, nie jestem w stanie go nazwać path.basename. Czy można nazwać go tak bezpośrednio, jak basename?

Author: Shai, 2009-03-24

19 answers

Uzyskanie nazwy pliku bez rozszerzenia:

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

Jeśli chodzi o problem z importem, rozwiązujesz go w ten sposób:

from os.path import basename

# now you can call it directly with basename
print(basename("/a/b/c.txt"))
 837
Author: Geo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-10-11 08:34:37

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'
 287
Author: gimel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-02-09 00:52:25
>>> print os.path.splitext(os.path.basename("hemanth.txt"))[0]
hemanth
 144
Author: hemanth.hm,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-06-23 10:17:04

A readable version, using Pathlib in Python 3.4+

from pathlib import Path

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

Wydrukuje:

Plik

Jeśli ścieżka może być dowiązaniem symbolicznym , to dodaj resolve()

Path('/root/dir/sub/file.ext').resolve().stem
 34
Author: bold,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-11-26 13:48:33

Dla kompletności, oto rozwiązanie pathlib dla Pythona 3.2+:

from pathlib import Path

print(Path(your_path).resolve().stem)
 31
Author: Morgoth,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-08-24 16:08:01

Jeśli chcesz zachować ścieżkę do pliku i po prostu usunąć rozszerzenie

>>> file = '/root/dir/sub.exten/file.data.1.2.dat'
>>> print ('.').join(file.split('.')[:-1])
/root/dir/sub.exten/file.data.1.2
 18
Author: ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-10-21 07:46:11

Os./ align = "left" / splitext () nie będzie działać, jeśli w rozszerzeniu Jest wiele kropek.

Na przykład obrazy.smoła.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

Możesz po prostu znaleźć indeks pierwszej kropki w nazwie podstawowej, a następnie pokroić nazwę Podstawową, aby uzyskać tylko nazwę pliku bez rozszerzenia.

>>> 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
 12
Author: Dheeraj Chakravarthi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-10-05 04:24:26

Ale nawet gdy importuję system operacyjny, nie jestem w stanie nazwać go path.basename. Czy można nazwać go tak bezpośrednio, jak basename?

import os, a następnie użyj os.path.basename

importing os nie oznacza, że możesz używać os.foo bez odwoływania się do os.

 11
Author: Devin Jeanpierre,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-03-24 16:45:02

@IceAdor ' s odnosi się do rsplit w komentarzu do rozwiązania @user2902201. rsplit jest najprostszym rozwiązaniem, które obsługuje wiele okresów.

Tutaj jest napisane:

file = 'my.report.txt'
print file.rsplit('.', 1)[0]
Mój.raport
 8
Author: dlink,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 20:09:13

Pomyślałem, że dorzucę odmianę do użycia os./ align = "left" / splitext bez potrzeby indeksowania tablicy.

Funkcja zawsze zwraca parę (root, ext), więc jest Bezpieczna w użyciu:

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

Przykład:

>>> import os
>>> path = 'my_text_file.txt'
>>> root, ext = os.path.splitext(path)
>>> root
'my_text_file'
>>> ext
'.txt'
 6
Author: ScottMcC,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-02-27 07:41:35

import os

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

To zwraca filename Bez extension (C:\Users\Public\Videos\Sample Filmy\Przyroda)

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

Teraz możesz dostać tylko filename z temp z

os.path.basename(temp)   #this returns just the filename (wildlife)
 4
Author: learncode,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-01-16 17:07:51

Procedura wielokrotnego rozszerzania. Działa dla ścieżek str i unicode. Działa w Pythonie 2 i 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)

Zachowanie:

>>> 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'
 3
Author: Lycan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-10-18 13:15:08

W systemie Windows użyłem prefiksu drivername, jak:

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

Dlatego, że nie potrzebuję litery dysku ani nazwy katalogu, używam:

>>> print(os.path.splitext(os.path.basename(s))[0])
akarmi
 2
Author: Zéiksz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-08-19 09:12:48
import os
path = "a/b/c/abc.txt"
print os.path.splitext(os.path.basename(path))[0]
 2
Author: user4949344,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-05-28 20:15:32

Https://docs.python.org/3/library/os.path.html

W Pythonie 3 pathlib " moduł pathlib oferuje obiekty ścieżki wysokiego poziomu." więc

>>> from pathlib import Path
>>> p = Path("/a/b/c.txt")
>>> print(p.with_suffix(''))
\a\b\c
>>> print(p.stem)
c
 2
Author: jjisnow,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-07-23 09:20:15

Możemy zrobić kilka prostych split / pop magia jak widać tutaj ( https://stackoverflow.com/a/424006/1250044 ), aby wyodrębnić nazwę pliku (z uwzględnieniem różnic w systemie Windows i 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
 1
Author: yckart,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:34:54

Dla wygody, prosta funkcja zawijająca dwie metody z os.path :

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

Testowany z Pythonem 3.5.

 0
Author: handle,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-09-22 20:23:28
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
 0
Author: shivendra singh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-06-01 13:37:07

Najprostszym sposobem rozwiązania tego problemu jest

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

Pozwala to zaoszczędzić czas i koszty obliczeniowe.

 0
Author: joseph nkoro,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-10-24 01:51:55