Python create file with folder

Работа с файлами в Python с помощью модуля OS

Обработка файлов в Python с помощью модуля os включает создание, переименование, перемещение, удаление файлов и папок, а также получение списка всех файлов и каталогов и многое другое.

В индустрии программного обеспечения большинство программ тем или иным образом обрабатывают файлы: создают их, переименовывают, перемещают и так далее. Любой программист должен обладать таким навыком. С этим руководством вы научитесь использовать модуль os в Python для проведения операций над файлами и каталогами вне зависимости от используемой операционной системы.

Важно знать, что модуль os используется не только для работы с файлами. Он включает массу методов и инструментов для других операций: обработки переменных среды, управления системными процессами, а также аргументы командной строки и даже расширенные атрибуты файлов, которые есть только в Linux.

Модуль встроенный, поэтому для работы с ним не нужно ничего устанавливать.

Вывод текущей директории

Для получения текущего рабочего каталога используется os.getcwd() :

import os # вывести текущую директорию print("Текущая деректория:", os.getcwd()) 

os.getcwd() возвращает строку в Юникоде, представляющую текущий рабочий каталог. Вот пример вывода:

Текущая деректория: C:\python3\bin 

Создание папки

Для создания папки/каталога в любой операционной системе нужна следующая команда:

# создать пустой каталог (папку) os.mkdir("folder") 

После ее выполнения в текущем рабочем каталоге тут же появится новая папка с названием «folder».

Читайте также:  Compile vim with python support

Если запустить ее еще раз, будет вызвана ошибка FileExistsError , потому что такая папка уже есть. Для решения проблемы нужно запускать команду только в том случае, если каталога с таким же именем нет. Этого можно добиться следующим образом:

# повторный запуск mkdir с тем же именем вызывает FileExistsError, # вместо этого запустите: if not os.path.isdir("folder"): os.mkdir("folder") 

Функция os.path.isdir() вернет True , если переданное имя ссылается на существующий каталог.

Изменение директории

Менять директории довольно просто. Проделаем это с только что созданным:

# изменение текущего каталога на 'folder' os.chdir("folder") 

Еще раз выведем рабочий каталог:

# вывод текущей папки print("Текущая директория изменилась на folder:", os.getcwd()) 
Текущая директория изменилась на folder: C:\python3\bin\folder 

Создание вложенных папок

Предположим, вы хотите создать не только одну папку, но и несколько вложенных:

# вернуться в предыдущую директорию os.chdir("..") # сделать несколько вложенных папок os.makedirs("nested1/nested2/nested3") 

Это создаст три папки рекурсивно, как показано на следующем изображении:

Создание вложенных папок

Создание файлов

Для создания файлов в Python модули не нужны. Можно использовать встроенную функцию open() . Она принимает название файла, который необходимо создать в качестве первого параметра и желаемый режим открытия — как второй:

# создать новый текстовый файл text_file = open("text.txt", "w") # запить текста в этот файл text_file.write("Это текстовый файл") 

w значит write (запись), a — это appending (добавление данных к уже существующему файлу), а r — reading (чтение). Больше о режимах открытия можно почитать здесь.

Переименование файлов

С помощью модуля os достаточно просто переименовать файл. Поменяем название созданного в прошлом шаге.

# переименовать text.txt на renamed-text.txt os.rename("text.txt", "renamed-text.txt") 

Функция os.rename() принимает 2 аргумента: имя файла или папки, которые нужно переименовать и новое имя.

Перемещение файлов

Функцию os.replace() можно использовать для перемещения файлов или каталогов:

# заменить (переместить) этот файл в другой каталог os.replace("renamed-text.txt", "folder/renamed-text.txt") 

Стоит обратить внимание, что это перезапишет путь, поэтому если в папке folder уже есть файл с таким же именем ( renamed-text.txt ), он будет перезаписан.

Список файлов и директорий

# распечатать все файлы и папки в текущем каталоге print("Все папки и файлы:", os.listdir()) 

Функция os.listdir() возвращает список, который содержит имена файлов в папке. Если в качестве аргумента не указывать ничего, вернется список файлов и папок текущего рабочего каталога:

Все папки и файлы: ['folder', 'handling-files', 'nested1', 'text.txt'] 

А что если нужно узнать состав и этих папок тоже? Для этого нужно использовать функцию os.walk() :

# распечатать все файлы и папки рекурсивно for dirpath, dirnames, filenames in os.walk("."): # перебрать каталоги for dirname in dirnames: print("Каталог:", os.path.join(dirpath, dirname)) # перебрать файлы for filename in filenames: print("Файл:", os.path.join(dirpath, filename)) 

os.walk() — это генератор дерева каталогов. Он будет перебирать все переданные составляющие. Здесь в качестве аргумента передано значение «.», которое обозначает верхушку дерева:

Каталог: .\folder Каталог: .\handling-files Каталог: .\nested1 Файл: .\text.txt Файл: .\handling-files\listing_files.py Файл: .\handling-files\README.md Каталог: .\nested1\nested2 Каталог: .\nested1\nested2\nested3 

Метод os.path.join() был использован для объединения текущего пути с именем файла/папки.

Удаление файлов

# удалить этот файл os.remove("folder/renamed-text.txt") 

os.remove() удалит файл с указанным именем (не каталог).

Удаление директорий

С помощью функции os.rmdir() можно удалить указанную папку:

# удалить папку os.rmdir("folder") 

Для удаления каталогов рекурсивно необходимо использовать os.removedirs() :

# удалить вложенные папки os.removedirs("nested1/nested2/nested3") 

Это удалит только пустые каталоги.

Получение информации о файлах

Для получения информации о файле в ОС используется функция os.stat() , которая выполняет системный вызов stat() по выбранному пути:

open("text.txt", "w").write("Это текстовый файл") # вывести некоторые данные о файле print(os.stat("text.txt")) 
os.stat_result(st_mode=33206, st_ino=14355223812608232, st_dev=1558443184, st_nlink=1, st_uid=0, st_gid=0, st_size=19, st_atime=1575967618, st_mtime=1575967618, st_ctime=1575966941) 

Это вернет кортеж с отдельными метриками. В их числе есть следующие:

    • st_size — размер файла в байтах
    • st_atime — время последнего доступа в секундах (временная метка)
    • st_mtime — время последнего изменения
    • st_ctime — в Windows это время создания файла, а в Linux — последнего изменения метаданных

    Для получения конкретного атрибута нужно писать следующим образом:

    # например, получить размер файла print("Размер файла:", os.stat("text.txt").st_size) 

    Выводы

    Работать с файлами и каталогами в Python очень просто. Не имеет значения даже используемая операционная система, хотя отдельные уникальные для системы функции можно использовать: например, os.chown() или os.chmod() в Linux. Более подробно эта тема освещена в официальной документации Python.

    Источник

    Creating and saving files in a new directory in Python

    From-Locals

    The following sections explain how to create and save a new file in Python using a new directory (folder) as the destination.

    • Error when specifying a non-existent directory with open() ( FileNotFoundError )
    • os.makedirs() Create a directory
    • Example code to create a new file with a destination

    The following is an example of a text file.

    When storing images, it depends on the library whether you can specify a path that includes a non-existent directory (or whether it will automatically create one if it does not exist).
    FileNotFoundError If this error occurs, you can create a new directory with os.madeirs() before executing the function to save, as in the following example.

    Error when specifying a non-existent directory with open()(FileNotFoundError)

    When creating a new file with the built-in function open(), an error occurs if a path containing a new directory (a directory that does not exist) is specified as the first argument as the destination. ( FileNotFoundError )

    open('not_exist_dir/new_file.txt', 'w') # FileNotFoundError 

    The first argument of open() can be an absolute path or a path relative to the current directory.

    For the basic usage of open(), such as creating a new file in an existing directory, or overwriting or appending to an existing file, refer to the following article.

    Create a directory(os.makedirs())

    When creating a new file in a non-existent directory, it is necessary to create the directory before open().

    If you are using Python 3.2 or later, it is convenient to use os.makedirs() with the argument exist_ok=True. Even if the target directory already exists, no error will occur and the directory can be created at once.

    import os os.makedirs(new_dir_path, exist_ok=True) 

    If you have an older version of Python and do not have the argument exist_ok in os.makedirs(), you will get an error if you specify the path to a directory that exists, so use os.path.exists() to check for the existence of the directory first.

    if not os.path.exists(new_dir_path): os.makedirs(new_dir_path) 

    See the following article for details.

    Example code to create a new file with a destination

    The following is a code example of a function that creates and saves a new file by specifying the destination directory.

    The first argument dir_path is the path of the destination directory, the second argument filename is the name of the new file to be created, and the third argument file_content is the content to be written, each specified as a string.

    If the specified directory does not exist, create a new one.

    import os def save_file_at_dir(dir_path, filename, file_content, mode='w'): os.makedirs(dir_path, exist_ok=True) with open(os.path.join(dir_path, filename), mode) as f: f.write(file_content) 
    save_file_at_dir('new_dir/sub_dir', 'new_file.txt', 'new text') 

    In this case, the file new_file.txt with the content “new text” will be created in new_dir\sub_dir. In other words, the following file will be newly created. new_dir/sub_dir/new_file.txt

    Concatenating directory and file names with os.path.join().

    Also, the mode of open() is specified as an argument. For text files, the default ‘w’ is fine, but if you want to create a binary file, set mode=’wb’.

    Источник

    Python Create Text File in Specific Directory Example

    This post is focused on python create text file in specific directory. If you have a question about how to create a text file in a directory in python then I will give a simple example with a solution. This example will help you python create text file in specific folder. I am going to show you about python create text file in specific directory.

    If you need to store your newly created txt file in a specific directory then I will give you a simple example to do this. In this example, we will create text file using open() and write() function. Then we will store «readme.txt» text file in «files» folder. Without any further ado, let’s see below code example.

    You can use these examples with python3 (Python 3) version.

    textFilePath = "files/readme.txt" # create new text file code with open(textFilePath, 'w') as f: f.write('New text file content line!') print("New text file created successfully!")

    It will create readme.txt file in «files» folder with following text.

    New text file content line!

    Hardik Savani

    I’m a full-stack developer, entrepreneur and owner of Aatman Infotech. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.

    We are Recommending you

    • Python Create an Empty Text File Example
    • How to Create Text File in Python?
    • Python Convert List into String with Commas Example
    • Python Split String into List of Characters Example
    • How to Get Unique Elements from List in Python?
    • Python Delete Files Matching Pattern Example
    • Python Delete Folder and Files Recursively Example
    • Python Post Request with Basic Authentication Example
    • Python Create Zip Archive from Directory Example
    • Python List All Dates Between Two Dates Example
    • How to Check if Today is Wednesday or not in Python?
    • How to Add Minutes to DateTime in Python?

    Источник

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