Путь до файла python linux

How do I get the full path of the current file’s directory? [duplicate]

__file__ is not defined when you run python as an interactive shell. The first piece of code in your question looks like it’s from an interactive shell, but would actually produce a NameError , at least on python 2.7.3, but others too I guess.

Why. is. this. so. hard. There are like a dozen SO threads on this topic. Python: «Simple is better than complex. There should be one— and preferably only one —obvious way to do it.»

@eric it isn’t hard, and the existence of multiple questions isn’t evidence of something being hard — it’s evidence of people not doing good research, of question titles being suboptimal for SEO, and/or of people failing to close duplicates that should be closed.

12 Answers 12

The special variable __file__ contains the path to the current file. From that we can get the directory using either pathlib or the os.path module.

Python 3

For the directory of the script being run:

import pathlib pathlib.Path(__file__).parent.resolve() 

For the current working directory:

import pathlib pathlib.Path().resolve() 

Python 2 and 3

For the directory of the script being run:

import os os.path.dirname(os.path.abspath(__file__)) 

If you mean the current working directory:

import os os.path.abspath(os.getcwd()) 

Note that before and after file is two underscores, not just one.

Also note that if you are running interactively or have loaded code from something other than a file (eg: a database or online resource), __file__ may not be set since there is no notion of «current file». The above answer assumes the most common scenario of running a python script that is in a file.

References

abspath() is mandatory if you do not want to discover weird behaviours on windows, where dirname(file) may return an empty string!

@DrBailey: no, there’s nothing special about ActivePython. __file__ (note that it’s two underscores on either side of the word) is a standard part of python. It’s not available in C-based modules, for example, but it should always be available in a python script.

@cph2117: this will only work if you run it in a script. There is no __file__ if running from an interactive prompt. \

Using Path from pathlib is the recommended way since Python 3:

from pathlib import Path print("File Path:", Path(__file__).absolute()) print("Directory Path:", Path().absolute()) # Directory of current working directory, not __file__ 

Note: If using Jupyter Notebook, __file__ doesn’t return expected value, so Path().absolute() has to be used.

Читайте также:  Linux run command on mount

That is correct @YellowPillow, Path(__file__) gets you the file. .parent gets you one level above ie the containing directory. You can add more .parent to that to go up as many directories as you require.

Sorry I should’ve have made this clearer, but if Path().absolute() exists in some module located at path/to/module and you’re calling the module from some script located at path/to/script then would return path/to/script instead of path/to/module

Path(__file__) doesn’t always work, for example, it doesn’t work in Jupyter Notebook. Path().absolute() solves that problem.

from pathlib import Path path = Path(__file__).parent.absolute() 
  • Path(__file__) is the path to the current file.
  • .parent gives you the directory the file is in.
  • .absolute() gives you the full absolute path to it.

Using pathlib is the modern way to work with paths. If you need it as a string later for some reason, just do str(path) .

This should be the accepted answer as of 2019. One thing could be mentioned in the answer as well: one can immediately call .open() on such a Path object as in with Path(__file__).parent.joinpath(‘some_file.txt’).open() as f:

The other issue with some of the answers (like the one from Ron Kalian, if I’m not mistaken), is that it will give you the current directory, not necessarily the file path.

import os dir_path = os.path.dirname(os.path.realpath(__file__)) 
import os print(os.path.dirname(__file__)) 

Sorry but this answer is incorrect, the correct one is the one made by Bryan `dirname(abspath(file)). See comments for details.

I found the following commands return the full path of the parent directory of a Python 3 script.

Python 3 Script:

#!/usr/bin/env python3 # -*- coding: utf-8 -*- from pathlib import Path #Get the absolute path of a Python3.6 and above script. dir1 = Path().resolve() #Make the path absolute, resolving any symlinks. dir2 = Path().absolute() #See @RonKalian answer dir3 = Path(__file__).parent.absolute() #See @Arminius answer dir4 = Path(__file__).parent print(f'dir1=\ndir2=\ndir3=\ndir4=') 
  1. dir1 and dir2 works only when running a script located in the current working directory, but will break in any other case.
  2. Given that Path(__file__).is_absolute() is True , the use of the .absolute() method in dir3 appears redundant.
  3. The shortest command that works is dir4.

A bare Path() does not provide the script/module directory. It is equivalent to Path(‘.’) – the current working directory. This is equivalent only when running a script located in the current working directory, but will break in any other case.

USEFUL PATH PROPERTIES IN PYTHON:

from pathlib import Path #Returns the path of the current directory mypath = Path().absolute() print('Absolute path : <>'.format(mypath)) #if you want to go to any other file inside the subdirectories of the directory path got from above method filePath = mypath/'data'/'fuel_econ.csv' print('File path : <>'.format(filePath)) #To check if file present in that directory or Not isfileExist = filePath.exists() print('isfileExist : <>'.format(isfileExist)) #To check if the path is a directory or a File isadirectory = filePath.is_dir() print('isadirectory : <>'.format(isadirectory)) #To get the extension of the file fileExtension = mypath/'data'/'fuel_econ.csv' print('File extension : <>'.format(filePath.suffix)) 

OUTPUT: ABSOLUTE PATH IS THE PATH WHERE YOUR PYTHON FILE IS PLACED

Читайте также:  Дота 2 для линукса

Absolute path : D:\Study\Machine Learning\Jupitor Notebook\JupytorNotebookTest2\Udacity_Scripts\Matplotlib and seaborn Part2

File path : D:\Study\Machine Learning\Jupitor Notebook\JupytorNotebookTest2\Udacity_Scripts\Matplotlib and seaborn Part2\data\fuel_econ.csv

Источник

Как прописать на Python путь к файлу в Windows, Mac и Linux

Одним из маленьких раздражителей в программировании является то, что путь к файлу в Microsoft Windows строится с использованием символа обратной косой черты между именами папок, в то время как почти все другие ОС используют прямую:

Путь к файлу в Windows: C:\some_folder\some_file.txt В большинстве других ОС: /some_folder/some_file.txt

Это случайность компьютерной истории начала 1980-х годов. В первой версии MS-DOS для указания параметров командной строки использовался символ прямой косой черты. Когда Microsoft добавила поддержку папок в MS-DOS 2.0, символ прямой косой черты был уже занят, поэтому вместо него использовалась обратная косая черта. Тридцать пять лет спустя мы по-прежнему сталкиваемся с этой несовместимостью.

Если вы хотите, чтобы ваш код на Python работал как на Windows, так и на Mac/Linux, вам придется решать подобные проблемы, связанные с конкретной платформой. К счастью, в Python 3 есть новый модуль pathlib , который делает работу с файлами практически безболезненной.

Давайте рассмотрим различные способы обработки путей к именам файлов и узнаем, как pathlib может сделать вашу жизнь лучше!

Неправильное решение: построить путь к файлу вручную

Допустим, у вас есть папка, содержащая файл, который вы хотите открыть в вашей программе Python:

Путь к файлу в структуре директорий

Сделать так будет неправильно:

data_folder = "source_data/text_files/" file_to_open = data_folder + "raw_data.txt" f = open(file_to_open) print(f.read())

Обратите внимание, что я жестко закодировал путь к файлу, используя прямые слэши в стиле Unix, поскольку я работаю на Mac. Это разозлит пользователей Windows.

Технически этот код будет работать под Windows, потому что в Python есть хак, который распознает любой вид слэша, когда вы вызываете open() под Windows. Но полагаться на это не стоит. Если вы используете тип слэша, не подходящий для ОС, не все библиотеки Python будут работать, особенно если они взаимодействуют с внешними программами или библиотеками.

А поддержка Python для смешивания типов слэшей – это хак только для Windows, который не работает в обратном направлении. Использование обратных слешей в коде будет полностью провальным на Mac:

data_folder = "source_data\\text_files\\" file_to_open = data_folder + "raw_data.txt" f = open(file_to_open) print(f.read()) # На Mac этот код выбросит исключение: # FileNotFoundError: [Errno 2] No such file or directory: 'source_data\\text_files\\raw_data.txt'

По этим и другим причинам написание кода с жестко закодированными строками путей – это то, что заставит других программистов смотреть на вас с большим подозрением. В общем, нужно стараться избегать этого.

Старое решение: построить путь к файлу при помощи модуля os.path

Модуль os.path в Python имеет множество инструментов для решения ОС-специфичных проблем с файловой системой.

Вы можете использовать os.path.join() для построения строки пути, используя нужный вид слэша для текущей операционной системы:

import os.path data_folder = os.path.join("source_data", "text_files") file_to_open = os.path.join(data_folder, "raw_data.txt") f = open(file_to_open) print(f.read())

Этот код будет отлично работать как на Windows, так и на Mac. Проблема в том, что его сложно использовать. Выписывать os.path.join() и передавать каждую часть пути в виде отдельной строки – многословно и неинтуитивно.

Читайте также:  Astra linux разделить диск

Поскольку большинство функций в модуле os.path так же неудобны в использовании, разработчики часто “забывают” их использовать. Это приводит к множеству кроссплатформенных ошибок и недовольству пользователей.

Лучшее решение: использовать pathlib в Python 3

В Python 3.4 появилась новая стандартная библиотека с модулем pathlib для работы с файлами и путями – и это замечательно!

Теперь вам достаточно передать путь к файлу или его имя в новый объект Path() , используя прямые косые черты, а все остальное pathlib сделает сам:

from pathlib import Path data_folder = Path("source_data/text_files/") file_to_open = data_folder / "raw_data.txt" f = open(file_to_open) print(f.read())

Обратите внимание на два момента:

  • С функциями pathlib нужно использовать прямые слэши. Объект Path() преобразует их в правильный вид слэша для текущей операционной системы. Отлично!
  • Если вы хотите дополнить путь к файлу, можно использовать оператор / непосредственно в коде. Попрощайтесь с беспрестанным набором os.path.join(a, b) .

И даже если бы это было всё, на что способен pathlib , это уже было бы отличным дополнением к Python. Но этот модуль способен на большее!

Например, мы можем прочитать содержимое текстового файла, не возясь с его открытием и закрытием:

from pathlib import Path data_folder = Path("source_data/text_files/") file_to_open = data_folder / "raw_data.txt" print(file_to_open.read_text())

Фактически, pathlib делает большинство стандартных операций с файлами быстрыми и простыми:

from pathlib import Path filename = Path("source_data/text_files/raw_data.txt") print(filename.name) # Выводит "raw_data.txt" print(filename.suffix) # Выводит "txt" print(filename.stem) # Выводит "raw_data" if not filename.exists(): print("Oops, file doesn't exist!") else: print("Yay, the file exists!")

Вы даже можете использовать pathlib для явного преобразования пути Unix в путь в формате Windows:

from pathlib import Path, PureWindowsPath filename = Path("source_data/text_files/raw_data.txt") # Конвертировать путь в формат Windows path_on_windows = PureWindowsPath(filename) print(path_on_windows) # Вывод: # source_data\text_files\raw_data.txt

И если вы хотите действительно безопасно использовать обратные слеши в своем коде, вы можете объявить свой путь к файлу в формате Windows, и pathlib преобразует его для работы в текущей операционной системе:

from pathlib import Path, PureWindowsPath # Я явно объявил мой путь в формате Windows, чтобы использовать в нем прямые слэши. filename = PureWindowsPath("source_data\\text_files\\raw_data.txt") # Конвертировать путь в подходящий для текущей ОС формат correct_path = Path(filename) print(correct_path) # Выводит "source_data/text_files/raw_data.txt" на Mac и Linux # Выводит "source_data\text_files\raw_data.txt" на Windows

Проявив смекалку, можно использовать pathlib даже для разрешения относительных путей к файлам, разбора путей к сетевым ресурсам и генерации URL file://. Вот пример из всего пары строк кода, которые откроют локальный файл в вашем браузере:

from pathlib import Path import webbrowser filename = Path("source_data/text_files/raw_data.txt") webbrowser.open(filename.absolute().as_uri())

Это был лишь небольшой обзор pathlib . Этот модуль – отличная замена для множества различных функций, связанных с файлами, которые раньше были разбросаны по разным модулям Python. Проверьте!

1 комментарий к “Как прописать на Python путь к файлу в Windows, Mac и Linux”

Источник

Оцените статью
Adblock
detector