{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Python для сбора данных\n", "\n", "*Алла Тамбовцева, НИУ ВШЭ*" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Работа с файлами: доступ и изменение" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Импортируем модуль `os` (от *operating system*), который позволяет работать с локальными (т.е. находящимися на компьютере) файлами и папками. " ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "import os" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Для начала определим рабочую папку – папку, которая используется по умолчанию (из неё по умолчанию запускается Jupyter, в неё сохраняются файлы и прочее, именно она отображается во вкладке *Home*)." ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'/Users/allat/Desktop'" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "os.getcwd() # от get current working directory" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "На Windows в начале строки будет название диска (`C:` или `D:`), плюс, слэши могут быть обратными (`\\` или `\\\\`). В дальнейшем при создании папки или при указании пути к папке/файлу нужно помнить, что Python распознаёт только прямые слэши `/` (на Windows ещё двойные `\\\\`, но иногда бывают сбои)." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Добавим пустую папку на рабочий стол (`Desktop`) и назовём её `to-test`:" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [], "source": [ "os.mkdir('/Users/allat/Desktop/to-test')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Совет:** если работаете с такого рода операциями впервые (никогда не создавали/удаляли файлы и папки через командную строку или подобные), лучше потестить всё в специально созданной папке или работать с копиями файлов. Python не будет уточнять, действительно ли вы хотите удалить файл или заменить файл новым с таким же названием, он молча удалит его или перезапишет. Будьте бдительны!" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Сделаем только что созданную папку рабочей:" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [], "source": [ "os.chdir('/Users/allat/Desktop/to-test') # chdir - от change directory" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Посмотрим на содержимое этой папки:" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[]" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "os.listdir()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Пока пусто. Это ожидаемо. Исправим: создадим два txt-файла, один пустой, а другой – с двумя строками." ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [], "source": [ "f1 = open('file1.txt', 'w')\n", "f1.close()\n", "f2 = open('file2.txt', 'w')\n", "\n", "# вписываем строки file = f2\n", "print(\"Hello\", file = f2) \n", "print(\"World\", file = f2) \n", "f2.close()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Проверим теперь:" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['file2.txt', 'file1.txt']" ] }, "execution_count": 8, "metadata": {}, "output_type": "execute_result" } ], "source": [ "os.listdir() # появились!" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Функция `listdir()` возвращает список файлов/папок. По умолчанию, если ничего не указано в круглых скобках, \n", "возвращается содержимое текущей рабочей папки. Но в скобках можно указать путь к любой папке:" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['py-icef',\n", " 'allatambov.github.io',\n", " 'misc',\n", " '.nbgrader.log',\n", " '.DS_Store',\n", " 'PyMasters',\n", " 'LingData',\n", " 'py-dat18',\n", " 'RprogData',\n", " 'PyDat-0919',\n", " 'py-dat19',\n", " 'CognTech',\n", " 'py-basics-19',\n", " 'r20-homeworks',\n", " 'Py-programming-3',\n", " 'PyProg-2018',\n", " 'HSE-PEP',\n", " 'pydat19-ap',\n", " 'R-programming-3',\n", " 'rprog-2019',\n", " 'PsyMS']" ] }, "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ "os.listdir('/Users/allat/Documents/github')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Вернёмся к нашей папке и сохраним её содержимое одним списком:" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [], "source": [ "files = os.listdir()" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['file2.txt', 'file1.txt']" ] }, "execution_count": 11, "metadata": {}, "output_type": "execute_result" } ], "source": [ "files" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Проверим, что содержимое файла `file2.txt` изменилось. Воспользуемся методом `readlines()`, который считывает строки из текстового файла:" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['Hello\\n', 'World\\n']" ] }, "execution_count": 14, "metadata": {}, "output_type": "execute_result" } ], "source": [ "f = open('file2.txt', 'r') # r - для чтения\n", "f.readlines()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Сохраним строки в список `lines`:" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[]" ] }, "execution_count": 13, "metadata": {}, "output_type": "execute_result" } ], "source": [ "lines = f.readlines()\n", "lines" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Список оказался пустым! Дело в том, что метод `.readlines()` срабатывает один раз, когда мы его запускаем после загрузки файла через `open()`. Чтобы все же сохранить строки в список, еще раз прогоним строку с `open()`, в которой мы загружаем файл `f`, а потом ячейку с `lines`:" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [], "source": [ "f = open('file2.txt', 'r')" ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['Hello\\n', 'World\\n']" ] }, "execution_count": 16, "metadata": {}, "output_type": "execute_result" } ], "source": [ "lines = f.readlines()\n", "lines" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Символ для перехода на новую строку всегда будет сохраняться, его можно убрать с помощью метода `.strip()` для строк, который убирает лишние пробелы в начале и в конце строки." ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['Hello', 'World']" ] }, "execution_count": 17, "metadata": {}, "output_type": "execute_result" } ], "source": [ "[line.strip() for line in lines]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "На этом работу с модулем `os` пока можно закончить. " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Работа с файлами CSV и Excel\n", "\n", "Можно найти разные способы для загрузки файлов с данными в Python, но мы остановимся на самом простом – с помощью библиотеки `pandas`. Импортируем библиотеку:" ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [], "source": [ "import pandas as pd" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Начнем с формата CSV, который расшифровывается как *comma separated values*. Столбцы в таком файле по умолчанию отделяются друг от друга запятой. Например, такая таблица" ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
abc
0014
1952
\n", "
" ], "text/plain": [ " a b c\n", "0 0 1 4\n", "1 9 5 2" ] }, "execution_count": 19, "metadata": {}, "output_type": "execute_result" } ], "source": [ "small = pd.DataFrame([[0, 1, 4], [9, 5, 2]])\n", "small.columns = ['a', 'b', 'c']\n", "small" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "сохраненная в формате CSV, будет выглядеть так: \n", "\n", " a,b,c\n", " 0,1,4\n", " 9,5,2.\n", " \n", "Но разделитель столбцов в таблице может быть и другим, например, точкой с запятой:\n", "\n", " a;b;c\n", " 0;1;4\n", " 9;5;2.\n", " \n", "В таких случаях нам потребуется дополнительно выставлять параметр `sep = \";\"`, чтобы Python понимал, как правильно отделять один столбец от другого. \n", "\n", "Давайте сначала экспортируем датафрейм `small` в файл с расширением `.csv` и в файл с расширением `.xlsx`, а потом полученные файлы загрузим в Python." ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [], "source": [ "# экспортируем, теперь эти файлы лежат в рабочей папке\n", "\n", "small.to_csv('abc.csv')\n", "small.to_excel('abc.xlsx')" ] }, { "cell_type": "code", "execution_count": 21, "metadata": {}, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
Unnamed: 0abc
00014
11952
\n", "
" ], "text/plain": [ " Unnamed: 0 a b c\n", "0 0 0 1 4\n", "1 1 9 5 2" ] }, "execution_count": 21, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# импортируем\n", "\n", "dat = pd.read_csv(\"abc.csv\")\n", "dat" ] }, { "cell_type": "code", "execution_count": 22, "metadata": {}, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
Unnamed: 0abc
00014
11952
\n", "
" ], "text/plain": [ " Unnamed: 0 a b c\n", "0 0 0 1 4\n", "1 1 9 5 2" ] }, "execution_count": 22, "metadata": {}, "output_type": "execute_result" } ], "source": [ "dat2 = pd.read_excel(\"abc.xlsx\")\n", "dat2" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.7.4" } }, "nbformat": 4, "nbformat_minor": 2 }