- Python 3 Quick Tip: The easy way to deal with file paths on Windows, Mac and Linux
- The Wrong Solution: Building File Paths by Hand
- The Old Solution: Python’s os.path module
- The Better Solution: Python 3’s pathlib!
- Как задать путь к файлу в Python?
- Как задать путь к файлу в Python?
- Самый простой вариант — не самый верный!
- Указываем путь к файлу правильно!
- Задаем относительный путь с помощью Path!
- Задаем абсолютный путь с помощью Path
- А почему не os.path.join?
- Самая лучшая практика: работа с path в Python
- Все та же проблема: список папок и дисков
- Объединяем пути с помощью Pathlib
- Обработка пути с помощью os.walk
- Лучшее решение с os.walk и Pathlib
- 2. Using Python on Unix platformsВ¶
- 2.1. Getting and installing the latest version of PythonВ¶
- 2.1.1. On LinuxВ¶
- 2.1.2. On FreeBSD and OpenBSDВ¶
- 2.1.3. On OpenSolarisВ¶
- 2.2. Building PythonВ¶
- 2.3. Python-related paths and filesВ¶
- 2.4. MiscellaneousВ¶
- 2.5. Custom OpenSSLВ¶
Python 3 Quick Tip: The easy way to deal with file paths on Windows, Mac and Linux
Jan 31, 2018 · 4 min read
One of programming’s little annoyances is that Microsoft Windows uses a backslash character between folder names while almost every other computer uses a forward slash:
This is an accident of early 1980’s computer history. The first version of MS-DOS used the forward slash character for specifying command-line options. When Microsoft added support for folders in MS-DOS 2.0, the forward slash character was already taken so they used a backslash instead. Thirty-five years later, we are still stuck with this incompatibility.
If you want your Pyt h on code to work on both Windows and Mac/Linux, you’ll need to deal with these kinds of platform-specific issues. Luckily, Python 3 has a new module called pathlib that makes working with files nearly painless.
Let’s take a quick look at the different ways of handling filename paths and see how pathlib can make your life better!
The Wrong Solution: Building File Paths by Hand
Let’s say you have a data folder that contains a file that you want to open in your Python program:
This is the wrong way to code it in Python:
Notice that I’ve hardcoded the path using Unix-style forward slashes since I’m on a Mac. This will make Windows users angry.
Technically this code will still work on Windows because Python has a hack where it will recognize either kind of slash when you call open() on Windows. But even still, you shouldn’t depend on that. Not all Python libraries will work if you use wrong kind of slash on the wrong operating system — especially if they interface with external programs or libraries.
And Python’s support for mixing slash types is a Windows-only hack that doesn’t work in reverse. Using backslashes in code will totally fail on a Mac:
For all these reasons and more, writing code with hardcoded path strings is the kind of thing that will make other programmers look at you with great suspicion. In general, you should try to avoid it.
The Old Solution: Python’s os.path module
Python’s os.path module has lots of tools for working around these kinds of operating system-specific file system issues.
You can use os.path.join() to build a path string using the right kind of slash for the current operating system:
This code will work perfectly on both Windows or Mac. The problem is that it’s a pain to use. Writing out os.path.join() and passing in each part of the path as a separate string is wordy and unintuitive.
Since most of the functions in the os.path module are similarly annoying to use, developers often “forget” to use them even when they know better. This leads to a lot of cross-platform bugs and angry users.
The Better Solution: Python 3’s pathlib!
Python 3.4 introduced a new standard library for dealing with files and paths called pathlib — and it’s great!
To use it, you just pass a path or filename into a new Path() object using forward slashes and it handles the rest:
Notice two things here:
- You should use forward slashes with pathlib functions. The Path() object will convert forward slashes into the correct kind of slash for the current operating system. Nice!
- If you want to add on to the path, you can use the / operator directly in your code. Say goodbye to typing out os.path.join(a, b) over and over.
And if that’s all pathlib did, it would be a nice addition to Python — but it does a lot more!
For example, we can read the contents of a text file without having to mess with opening and closing the file:
In fact, pathlib makes most standard file operations quick and easy:
You can even use pathlib to explicitly convert a Unix path into a Windows-formatted path:
And if you REALLY want to use backslashes in your code safely, you can declare your path as Windows-formatted and pathlib can convert it to work on the current operating system:
If you want to get fancy, you can even use pathlib to do things like resolve relative file paths, parse network share paths and generate file:// urls. Here’s an example that will open a local file in your web browser with just two lines a code:
This was just a tiny peak at pathlib. It’s a great replacement for lots of different file-related functionality that used to be scattered around different Python modules. Check it out!
Thanks for reading! If you are interested in Machine Learning (or just want to understand what it is), check out my Machine Learning is Fun! series or sign up for my newsletter:
You can also follow me on Twitter at @ageitgey or find me on LinkedIn.
Источник
Как задать путь к файлу в Python?
Как задать путь к файлу в Python?
Для решения задач, связанных с редактированием или чтением файла, необходимо сообщить интерпретатору Python имя нужного нам файла, а также адрес, по которому этот файл располагается. Существуют разные способы указания пути к файлу в Python: от самого простого, до самого правильного. Давайте выясним, чем эти варианты отличаются и почему простой вариант не годится на роль лучшего!
Самый простой вариант — не самый верный!
Внимание! У этого способа обнаружен недостаток!
Самый простой вариант задания пути выглядит как последовательность директорий, в которых находится файл, с именем самого файла, разделенные знаками слеша:
Пример относительного пути:
Где вместо «Files» и «info.txt» Вы напишите названия ваших директорий и имя вашего файла соответственно.
Пример абсолютного пути:
Где вместо «C:\Python\pythonw.exe\Files\info.txt», «home/my_comp/Files/» и «info.txt» Вы напишите названия ваших директорий и имя вашего файла соответственно.
Этот вариант рабочий, однако, один существенный недостаток лишил его внимания разработчиков. Проблема заключается в том, что заданные таким способом пути адаптированы только к одному виду операционной системы: к Линукс, либо к Windows, так как в Windows используются обратные слеши «\», а в Линукс — обычные «/». Из-за этого скрипт, показывавший отличные результаты в Windows, начнет жаловаться на отсутствие файлов по прописанному пути в Linux, и наоборот. А с абсолютным путем вообще все сложно: никакого диска «C:» в Линуксе нет. Скрипт опять будет ругаться! Что же делать? Правильно указать путь к файлу!
Указываем путь к файлу правильно!
Внимание! Годный вариант!
Python — умный змей, поэтому в его арсенале, начиная с 3.4 версии появился модуль pathlib, который позволяет вытворять самые приятные вещи с путями к файлу, стоит только импортировать его класс Path:
Кстати, если у вас не установлен модуль pathlib, это легко исправить с помощью команды:
Задаем относительный путь с помощью Path!
После того, как класс импортирован, мы получаем власть над слешами! Теперь вопрос о прямых и обратных слешах в разных операционных системах ложится на плечи Path. Используя Path, вы можете корректно задать относительный путь, который будет работать в разных системах.
Например, в случае расположения файлов, как на представленном изображении, относительный путь, определяемый в скрипте «main_script.py», сформируется автоматически из перечисленных в скобках составных частей. Pathlib инициализирует новый объект класса Path, содержимым которого станет сформированный для Вашей системы относительный путь (в Windows части пути будут разделены обратными слешами, в Linux — обычными):
Задаем абсолютный путь с помощью Path
- cwd() — возвращает путь к рабочей директории
- home() — возвращает путь к домашней директории
Полученную строку, содержащую путь к рабочей или домашней директории, объединим с недостающими участками пути при инициализации объекта класса Path :
Пример 1: с использованием функции cwd():
В данном случае путь к директории имеет вид: dir_path = «/home/molodec/python», а полный путь к файлу «docs.txt» будет иметь вид: «/home/molodec/python/files/info/docs.txt».
Представленный выше код можно оптимизировать и записать в одну строку:
Пример2: с использованием функции home():
В данном случае путь к директории имеет вид: dir_path = «/home/molodec», а полный путь к файлу ‘docs.txt’ будет иметь вид: «/home/molodec/files/info/docs.txt».
Сократим представленный выше код:
А почему не os.path.join?
А что же не так с заслуженным мастером по объединению путей os.path.join() и хранителем секретной информации о расположении рабочей директории os.getcwd()? Действительно, эти замечательные функции в составе модуля os довольно долго служили разработчикам Python верой и правдой. Их вполне можно использовать для определения пути к файлу. Однако, большим недостатком функции join() является невозможность принять для объединения более двух аргументов. Таким образом, чтобы присоединить к рабочей директории путь вида: ‘files/info/docs.txt’, приходится трижды обращаться к функции join(), не забывая при этом искусно жонглировать скобками. Выглядит это примерно так:
Казалось бы, ничего сложного. Однако, зачем громоздить лишние скобки, когда есть более лаконичный вариант с использованием модуля pathlib?
Подведем итог: начиная с версии Python 3.4, для задания пути к файлу рекомендуется использовать модуль pathlib с классом Path. Определить путь к рабочей директории можно с помощью функции cwd(), а путь к домашней директории подскажет функция home().
Источник
Самая лучшая практика: работа с path в Python
Все та же проблема: список папок и дисков
В последней статье мы использовали рекурсивную функцию размером менее 10 строк для решения проблемы сканирования папок и ранжирования файлов по дате изменения и размеру.
Теперь я подниму планку и покажу, как можно было сделать лучше.
Объединяем пути с помощью Pathlib
Старые идеи в новом обличье?
Предыдущее решение с соединением путей выглядело следующим образом:
Преимущество такого подхода заключается в том, что решение не зависит от операционной системы, и вам не нужно складывать строки с помощью оператора «+» или форматирования.
Тем не менее, здесь можно допустить ошибку, например, непреднамеренно или ошибочно определить путь к каталогу с помощью закрывающего разделителя.
Несмотря на то, что в этом примере показан рабочий код, неправильный разделитель приведет к ошибке при вызове этого пути. И такие ошибки могут возникать всякий раз, когда далекие от кода пользователи оперируют путями в конфигурационных файлах, не обращая внимания на соглашения.
В Python 3.4 появилось лучшее решение — модуль pathlib . Он обрабатывает функции файлов и папок модуля os с помощью объектно-ориентированного подхода.
Напомню, старый вариант выглядел вот так:
А вот альтернативный:
Оба варианта дают один и тот же результат. Так чем же второй вариант лучше?
Объектно-ориентированный и более устойчивый к ошибкам
Вызовы в основном являются объектно-ориентированными, нравится вам это или нет, но лично мне такой подход по душе. Здесь у нас есть такой объект, как определение path , у которого есть атрибуты и методы.
Однако пример с операторами перегрузки в данном случае более интересен:
Сначала разделение на два пути кажется недопустимым. Однако объект path был перегружен так, чтобы работать как объединенный путь.
В дополнение к этому синтаксическому сахару объекты path будут перехватывать другие типичные ошибки:
Такой вариант не только приятнее, но и устойчивее к неправильным входным данным. В дополнение к другим преимуществам код также не привязан к определенной операционной системе. Он определяет только generic объект path , который объявляется в системе Windows как WindowsPath , а в Linux как PosixPath .
Большинство функций, которые ожидают строку в качестве пути, могу работать непосредственно с путем. В редких случаях вам может понадобиться изменить объект просто с помощью str(Path) .
Обработка пути с помощью os.walk
В своей последней статье я использовал os.listdir , os.path.isdir и рекурсивную функцию для итерации по дереву путей и разграничения файлов и папок.
Но os.walk предлагает решение получше. Этот метод создает не список, а итератор, который можно вызывать построчно. В результате мы получим соответствующий путь к папке и список всех файлов по этому пути. Весь процесс происходит рекурсивно, поэтому вы получите все файлы одним вызовом.
Лучшее решение с os.walk и Pathlib
Если вы объедините два вышеупомянутых метода, то получите решение, которое будет более простым, полностью независимым от операционной системы, устойчивым к неправильным форматам путей и без явных рекурсий:
Если вам удастся улучшить этот вариант, не постесняйтесь рассказать мне об этом. Я был бы рад вашим отзывам!
Первую часть статьи можно найти здесь.
Также приглашаем всех желающих принять участие в бесплатном демо-уроке курса на тему «Три кита: map(), filter() и zip()».
Можно ли писать код, требующий циклов, но без циклов? Может ли он быть быстрее, чем, если бы мы использовали циклы в Python? Для реализации задуманного понадобится знание слов «callback», «iterator» и «lambda». Если интересно — присоединяйтесь!
Источник
2. Using Python on Unix platformsВ¶
2.1. Getting and installing the latest version of PythonВ¶
2.1.1. On LinuxВ¶
Python comes preinstalled on most Linux distributions, and is available as a package on all others. However there are certain features you might want to use that are not available on your distro’s package. You can easily compile the latest version of Python from source.
In the event that Python doesn’t come preinstalled and isn’t in the repositories as well, you can easily make packages for your own distro. Have a look at the following links:
for Debian users
for OpenSuse users
for Fedora users
for Slackware users
2.1.2. On FreeBSD and OpenBSDВ¶
FreeBSD users, to add the package use:
OpenBSD users, to add the package use:
For example i386 users get the 2.5.1 version of Python using:
2.1.3. On OpenSolarisВ¶
You can get Python from OpenCSW. Various versions of Python are available and can be installed with e.g. pkgutil -i python27 .
2.2. Building PythonВ¶
If you want to compile CPython yourself, first thing you should do is get the source. You can download either the latest release’s source or just grab a fresh clone. (If you want to contribute patches, you will need a clone.)
The build process consists of the usual commands:
Configuration options and caveats for specific Unix platforms are extensively documented in the README.rst file in the root of the Python source tree.
make install can overwrite or masquerade the python3 binary. make altinstall is therefore recommended instead of make install since it only installs exec_prefix /bin/python version .
2.3. Python-related paths and filesВ¶
These are subject to difference depending on local installation conventions; prefix ( $
For example, on most Linux systems, the default for both is /usr .
Recommended location of the interpreter.
prefix /lib/python version , exec_prefix /lib/python version
Recommended locations of the directories containing the standard modules.
prefix /include/python version , exec_prefix /include/python version
Recommended locations of the directories containing the include files needed for developing Python extensions and embedding the interpreter.
2.4. MiscellaneousВ¶
To easily use Python scripts on Unix, you need to make them executable, e.g. with
and put an appropriate Shebang line at the top of the script. A good choice is usually
which searches for the Python interpreter in the whole PATH . However, some Unices may not have the env command, so you may need to hardcode /usr/bin/python3 as the interpreter path.
To use shell commands in your Python scripts, look at the subprocess module.
2.5. Custom OpenSSLВ¶
To use your vendor’s OpenSSL configuration and system trust store, locate the directory with openssl.cnf file or symlink in /etc . On most distribution the file is either in /etc/ssl or /etc/pki/tls . The directory should also contain a cert.pem file and/or a certs directory.
Download, build, and install OpenSSL. Make sure you use install_sw and not install . The install_sw target does not override openssl.cnf .
Build Python with custom OpenSSL (see the configure –with-openssl and –with-openssl-rpath options)
Patch releases of OpenSSL have a backwards compatible ABI. You don’t need to recompile Python to update OpenSSL. It’s sufficient to replace the custom OpenSSL installation with a newer version.
Источник