I’m trying to store in a variable the name of the current file that I’ve opened from a folder.
How can I do that?
I’ve tried cwd = os.getcwd()
but this only gives me the path of the folder, and I need to store the name of the opened file.
Can you please help me?
Kara
6,08516 gold badges49 silver badges57 bronze badges
asked Nov 27, 2008 at 11:28
1
One more useful trick to add. I agree with original correct answer, however if you’re like me came to this page wanting the filename only without the rest of the path, this works well.
>>> f = open('/tmp/generic.png','r')
>>> f.name
'/tmp/generic.png'
>>> import os
>>> os.path.basename(f.name)
'generic.png'
answered Jun 10, 2014 at 15:30
James ErricoJames Errico
5,7761 gold badge19 silver badges16 bronze badges
Python 2.5.1 (r251:54863, Jul 31 2008, 22:53:39)
[GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> f = open('generic.png','r')
>>> f.name
'generic.png'
answered Nov 27, 2008 at 11:30
Vinko Vrsalovic♦Vinko Vrsalovic
329k53 gold badges333 silver badges371 bronze badges
2
Maybe this script is what you want?
import sys, os
print sys.argv[0]
print os.path.basename(sys.argv[0])
When I run the above script I get;
D:UserDataworkspacetempScript1.py
Script1.py
answered Nov 27, 2008 at 17:36
Rudiger WolfRudiger Wolf
1,76011 silver badges15 bronze badges
Use this code snippet to get the filename you are currently running (i.e .py
file):
target_file = inspect.currentframe().f_code.co_filename
kishkin
5,0671 gold badge26 silver badges40 bronze badges
answered Mar 31, 2020 at 6:59
Getting a filename from Python using a path is a complex process. i.e, In Linux or Mac OS, use “/” as separators of the directory while Windows uses “” for separating the directories inside the path. So to avoid these problems we will use some built-in package in Python.
File Structure: Understanding Paths
path name root ext /home/User/Desktop/file.txt /home/User/Desktop/file .txt /home/User/Desktop /home/User/Desktop {empty} file.py file .py .txt .txt {empty}
Here, ext stands for extension and has the extension portion of the specified path while the root is everything except ext part.
ext is empty if the specified path does not have any extension. If the specified path has a leading period (‘.’), it will be ignored.
Get filename without extension in Python
Get the filename from the path without extension split()
Python’s split() function breaks the given text into a list of strings using the defined separator and returns a list of strings that have been divided by the provided separator.
Python3
import
os
path
=
'D:homeRiot GamesVALORANTliveVALORANT.exe'
print
(os.path.basename(path).split(
'.'
)[
0
])
Output:
VALORANT
Get filename from the path without extension using Path.stem
The Python Pathlib package offers a number of classes that describe file system paths with semantics suitable for many operating systems. The standard utility modules for Python include this module. Although stem is one of the utility attributes that makes it possible to retrieve the filename from a link without an extension.
Python3
import
pathlib
path
=
'D:homeRiot GamesVALORANTliveVALORANT.exe'
name
=
pathlib.Path(path).stem
print
(name)
Output:
VALORANT
Get the filename from the path without extension using rfind()
Firstly we would use the ntpath module. Secondly, we would extract the base name of the file from the path and append it to a separate array. The code for the same goes like this. Then we would take the array generated and find the last occurrence of the “.” character in the string. Remember finding only the instance of “.” instead of the last occurrence may create problems if the name of the file itself contains “.”. We would find that index using rfind and then finally slice the part of the string before the index to get the filename. The code looks something like this. Again you can store those filenames in a list and use them elsewhere but here we decided to print them to the screen simply.
Python3
import
ntpath
paths
=
[
"E:Programming Source CodesPythonsample.py"
,
"D:homeRiot GamesVALORANTliveVALORANT.exe"
]
filenames
=
[]
for
path
in
paths:
filenames.append(ntpath.basename(path))
for
name
in
filenames:
k
=
name.rfind(
"."
)
print
(name[:k])
Output:
Get filename with entire path without extension
Get filename from the path without extension using rpartition()
Similar to how str.partition() and str.split operate, rpartition(). It only splits a string once, and that too in the opposite direction, as opposed to splitting it every time from the left side (From the right side).
Python3
path
=
'D:homeRiot GamesVALORANTliveVALORANT.exe'
print
(path.rpartition(
'.'
)[
0
])
Output:
D:homeRiot GamesVALORANTliveVALORANT
Get filename from the path without extension using splitext()
The os.path.splitext() method in Python is used to split the path name into a pair root and ext.
Python3
import
os
path
=
'D:homeRiot GamesVALORANTliveVALORANT.exe'
print
(os.path.splitext(path)[
0
])
Output:
D:homeRiot GamesVALORANTliveVALORANT
Get filename from the path without extension using rsplit()
Python String rsplit() method returns a list of strings after breaking the given string from the right side by the specified separator.
Python3
path
=
'D:homeRiot GamesVALORANTliveVALORANT.exe'
print
(path.rsplit(
'.'
,
1
)[
0
])
Output:
D:homeRiot GamesVALORANTliveVALORANT
Last Updated :
14 Sep, 2022
Like Article
Save Article
Путь, имя и расширение файла
-
Абсолютный путь к файлу
-
Имя файла
-
Без расширения
-
Расширение файла
Достаточно часто возникают ситуации, когда у нас есть полное имя файла, а требуется узнать его расширение. Или добавить нужное расширение, когда не известно, ввел его пользователь или нет. Иногда у нас есть относительный путь до файла, а требуется узнать абсолютный. Про основные методы работы с именем файла и будет эта статья.
Абсолютный путь к файлу
Для того чтобы узнать в Python абсолютный путь к файлу, потребуется воспользоваться библиотекой os. Её подключаем с помощью команды import os. В классе path есть метод abspath. Вот пример использования.
import os p = os.path.abspath('file.txt ') print(p) C:python3file.txt
Так же можно воспользоваться и стандартной библиотекой pathlib. Она вошла в состав основных библиотек, начиная с версии Python 3.4. До этого надо было ее инсталлировать с помощью команды pip install pathlib. Она предназначена для работы с путями файловой системы в разных ОС и отлично подойдет для решения данной задачи.
import pathlib p = pathlib.Path('file.txt ') print(p) C:python3file.txt
Имя файла
Чтобы узнать имя файла из полной строки с путем, воспользуемся методом basename модуля os.
import os name = os.path.basename(r'C:python3file.txt ') print(name) file.txt
Здесь перед строкой вставил r, чтобы подавить возможное возникновение служебных символов. Например, в данном случае если не указать r, то f считалось бы символом перевода страницы.
Без расширения
Теперь разберемся, как в Python узнать имя файла без расширения. Воспользуемся методом splittext. В этот раз для примера возьмем файл с двойным расширением, чтобы проверить, как будут в этой ситуации работать стандартны функции.
from os import path full_name = path.basename(r'C:python3file.tar.gz ') name = path.splitext(full_name)[0] print(name) file.tar
Видно, что последнее расширение архиватора gz было отброшено, в то время как расширение несжатого архива tar осталось в имени.
Если же нам нужно только имя, то можно отбросить все символы полученной строки, которые идут после первой точки. Символ точки тоже отбросим.
Дополним предыдущий пример следующим кодом:
index = name.index('.') print(name[:index]) file
Расширение файла
В Python получить расширение файла можно аналогичным образом с помощью той же функции splitext. Она возвращает кортеж. Первый элемент кортежа имя, а второй – расширение. В данном случае нам нужен второй элемент. Индекс второго элемента равен единице, так как отсчет их идет от нуля.
from os import path full_name = path.basename(r'C:python3file.tar.gz ') name = path.splitext(full_name)[1] print(name) .gz
Аналогично можно воспользоваться библиотекой pathlib. Воспользуемся методом suffix.
from pathlib import Path print(Path(r'C:python3file.tar.gz ').suffix) .gz
Но в нашем случае два расширения. Их можно узнать с помощью функции suffixes. Она возвращает список, элементами которого и будут расширения. Ниже приведен пример получения списка расширений.
from pathlib import Path print(Path(r'C:python3file.tar.gz ').suffixes) ['.tar', '.gz ']
Для того, чтобы получить имя файла или расширение из полного пути или для получения абсолютного пути к файлу используйте библиотеки os и pathlib. Лучше воспользоваться готовым решением из стандартой библиотеками, чем писать свое решение.
Допустим, у вас есть строка, представляющая абсолютный путь к файлу. Имя файла – последний элемент этого пути. Например, в абсолютном пути /home/username/downloads/my_file.txt часть my_file – собственно имя файла. В этой статье мы разберем, как, зная путь, получить имя файла при помощи Python.
import os # Имя файла с расширением file_name = os.path.basename('/root/file.ext') # Имя файла без расширения print(os.path.splitext(file_name)[0]) # Результат: # file
Функция basename()
выдает имя последнего файла/папки из пути, а splitext()
разделяет имя файла на имя и расширение. Иллюстрация работы splitext()
:
import os print(os.path.splitext('file.ext')) # Результат: # ('file', '.ext')
Использование модуля Path
from pathlib import Path print(Path('/root/file.ext').stem) # Результат: # file
Используя атрибут stem
модуля Path
, можно извлечь имя файла, как показано выше.
Это работает для Python 3.4 и выше.
Перевод статьи «Python Program to Get the File Name From the File Path».
В этом посте мы обсудим, как получить имя файла без расширения по указанному пути в Python.
1. Использование os.path.splitext()
функция
Стандартным решением является использование os.path.splitext(path)
function to split a path into a (root, ext) pair such that root + ext == path. This returns the path to the file without extension. If the file has multiple periods, leading periods are ignored.
import os dir = ‘/path/to/some/file.txt’ print(os.path.splitext(dir)[0]) # /путь/к/кому-то/ |
Скачать код
2. Использование str.rsplit()
функция
В качестве альтернативы вы можете использовать str.rsplit()
функция разделения на последний период.
dir = ‘/path/to/some/file.txt’ print(dir.rsplit(‘.’, 1)[0]) # /путь/к/кому-то/ |
Скачать код
3. Использование pathlib.Path.stem()
функция
Если вам не нужен полный путь, вы можете использовать pathlib
модуль в Python 3.4+. Вы можете использовать его stem
свойство, которое возвращает имя файла без его расширения:
from pathlib import Path dir = ‘/path/to/some/file.txt’ print(Path(dir).stem) # /путь/к/кому-то/ |
Скачать код
Вот и все, что нужно для получения имени файла без расширения в Python.
Спасибо за чтение.
Пожалуйста, используйте наш онлайн-компилятор размещать код в комментариях, используя C, C++, Java, Python, JavaScript, C#, PHP и многие другие популярные языки программирования.
Как мы? Порекомендуйте нас своим друзьям и помогите нам расти. Удачного кодирования 🙂