Copy files python windows

Копирование файла в Python

В наших предыдущих руководствах мы изучили некоторые операции с файлами Python, такие как чтение, запись и удаление.

Мы можем скопировать файл в Python, используя различные методы в нижеперечисленных модулях,

  • модуль shutil
  • модуль os
  • модуль subprocess

В этом руководстве мы научимся использовать различные методы, предоставляемые вышеуказанными модулями, для копирования файла в Python.

1 shutil модуль

Модуль shutil предоставляет несколько простых в использовании методов, с помощью которых мы можем удалить или скопировать файл. Давайте посмотрим на различные методы, определенные в этом модуле, специально используемые для копирования.

1 copyfileobj()

Метод copyfileobj() копирует содержимое исходного файла в целевой файл, используя соответствующие файловые объекты. Давайте посмотрим на код ниже,

Примечание: объекты файлов должны указывать на позиции 0 (начальную позицию) для соответствующих исходных и целевых файлов, чтобы скопировать все содержимое.

2 copyfile()

Метод copyfile() копирует содержимое из исходного файла в целевой файл, используя пути к файлам. Он возвращает путь к целевому файлу. Путь к целевому файлу должен быть доступен для записи, иначе возникнет исключение OSerror.

Следует иметь в виду, что метод позволяет использовать только пути к файлам, а не каталоги.

3 copy()

Этот метод копирует исходный файл в целевой файл или целевой каталог. В отличие от copyfile() , метод copy() позволяет использовать целевой каталог в качестве аргумента, а также копирует права доступа к файлу. copy() возвращает путь к целевому файлу после копирования содержимого.

В целевом месте назначения создается файл с именем file.txt со всем содержимым и разрешениями, скопированными из /Users/test/file.txt.

4 copy2()

Метод copy2() используется точно так же, как метод copy() . Они также работают аналогичным образом, за исключением того факта, что copy2() также копирует метаданные из исходного файла.

2 Модуль os

1 popen()

Метод popen() создает канал к команде cmd. Метод возвращает файловый объект, подключенный к каналу cmd. Взгляните на код ниже,

С помощью этого метода мы можем выполнять другие обычные команды.

2 system()

Метод system() напрямую вызывает и выполняет аргумент команды в подоболочке. Его возвращаемое значение зависит от ОС, в которой запущена программа. Для Linux это статус выхода, тогда как для Windows это значение, возвращаемое системной оболочкой.

Операции с файлами

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

Проверка существования файла

Избежать досадных ошибок при работе с текстовым документом, которые могут быть связаны с его отсутствием на жестком диске компьютера, поможет метод exists из модуля os. Его вызов позволяет проверить в Python существование файла по указанному пути, получив в качестве результирующего ответа булево значение True или False. Чтобы воспользоваться данным методом, необходимо прежде всего подключить библиотеку os, а затем вызвать exists у класса path. Следующий пример на Python показывает проверку наличия файлов test.txt и test10.txt в корневом каталоге жесткого диска D. Функция print показывает, что в наличии на D только первый документ.

Иногда при работе с документами возникает потребность в проверке не только существования некоего объекта по заданному пути. Функция isfile из уже упомянутой здесь библиотеки os дает программисту возможность убедиться в том, что полученный по определенному адресу объект на жестком диске компьютера является файлом, а не папкой. Данный метод также находится в классе path. В следующем примере показывается реакция isfile на получение в качестве аргумента файла test.txt и каталога folder в корне D. Как видно из результатов работы функции print, в первом случае отображается True, а затем False.

Проверить наличие файла по указанному адресу можно и с помощью функции open, применив дополнительно конструкцию with as. Данный метод производит открытие документа для того, чтобы программа могла взаимодействовать с его содержимым. Если функция open смогла без ошибок выполниться, это означает, что по переданному ей в качестве аргумента пути имеется файл. Если же произойдет исключение, то файл не удалось открыть. Это еще не говорит о том, что его нету. Возможно, к примеру, не достаточно прав доступа к нему. В приведенном ниже примере программа сообщает о наличии искомого документа при помощи метода print. Как видно из результатов, на экран выводится сообщение file is open.

Копирование файла

Библиотека под названием shutil включает в себя несколько полезных функций для создания копий объектов на жестком диске. Чтобы быстро скопировать файл в исходный каталог, стоит воспользоваться методом copyfile, предварительно подключив модуль shutil. В роли первого аргумента здесь выступает оригинальный документ, в то время как вторым параметром нужно поставить предполагаемый новый файл. Стоит учитывать, что копируется только содержимое, но не метаданные. В следующем примере происходит копирование данных из файла test.txt в test2.txt на диске D. Функция copyfile также возвращает адрес созданного документа.

Читайте также:  Программирования для linux примеры

Встроенный метод copy из модуля shutil позволяет в Python копировать файл в указанную папку, сохраняя при этом его изначальное имя. Приведенный ниже пример кода демонстрирует копирование информации из test.txt в объект, который находится на диске D в каталоге под названием folder. Как и в предыдущем случае с функцией copyfile, переносятся только внутренние данные, но не сведения о дате создания и редактирования документа.

Чтобы полностью скопировать информацию из текстового файла, а также все сведения о нем, необходимо воспользоваться готовым методом copy2. Способ его применения такой же, как и в случае с функцией copy. На месте первого параметра здесь размещается адрес изначального файла, в то время как второй аргумент сообщает локацию и название нового документа. Ниже показан пример, где содержимое и метаданные копируются в test2.txt из папки folder.

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

Избавиться от объекта, если известно его имя и точное расположение на диске, очень легко. С этой задачей поможет справиться метод remove из уже упомянутой ранее библиотеки os. Все, что требуется сделать, это передать ей в качестве параметра полный адрес ненужного файла, не забыв для начала подключить модуль os. Ниже приведен пример того, как с помощью скрипта Python удалить файл test.txt в корне диска D.

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

Определить точный размер любого объекта на жестком диске можно с помощью стандартной функции getsize из модуля os, которая возвращает величину файла в байтах. Выполнив импорт библиотеки os, необходимо вызвать метод класса path. Аргументом тут выступает расположение документа в памяти компьютера. Согласно результатам выполнения getsize, размер test.txt составляет 7289. Метод print выводит это на экран.

Вычислить размер файла в Python можно и другим способом, открыв его при помощи open, после чего вызвав функцию seek. Ей необходимо передать в качестве параметра область для чтения данных, начиная от начала файла до его конца. В итоге следует вызвать метод tell через ссылку на текстовый файл, а затем отправить результат его работы в print для вывода в консоль.

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

Изменить название документа можно не только благодаря средствам системы, но и с помощью готовых функций модуля os. С этой задачей хорошо справляется метод rename, принимающий в качестве параметров исходное и новое имя файла. Следующий пример показывает работу с документом test.txt в корневом каталоге диска D, который переименовывается в test1.txt.

Аналогично, можно в Python переименовать файл с помощью метода move из модуля shutil. Подключив данную библиотеку, достаточно лишь передать функции местоположение и новое имя документа. Код программы, где продемонстрировано переименование test.txt в test1.txt, находится ниже.

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

Копирование файлов в Python

Перемещать и копировать файлы по каталогам нам поможет функции модуля shutil. Подключаем модуль shutil в начале нашего скрипта на Python, потом уже получим доступ к его функциям. Функции модуля shutil не ограничиваются только на копирование и перемещение, мы обсудим разные методики использования функции даного модуля.

Функция copyfile(Копируемый файл, путь куда копируем)

Функция copy(Копируемый файл, куда копируем)

Копирует файл вместе с его правами. В случае если файл уже существовал, он будет перезаписан. Неудачное копирование вызовет исключение IOError.

Сайт avi1.ru поможет Вам заказать платные лайки в Ютубе с очень большими оптовыми скидками. Торопитесь, пока действует предложение. Также на страницах данного сервиса Вы сможете найти все, что нужно для продвижения в Ютубе: подписчиков, просмотры и т. д.

Функция copy2(Копируемый файл, путь куда копируем)

Копирует файл вместе с его методанными. Если файл уже существует, он будет перезаписан.

Перемещение файла, функция move(путь к файлу, путь куда перемещать)

Копирует файл из указанного места, создает новый или перезаписывает уже существующий по новому пути. После выполнения копирования, копируемый файл удаляется. Бывает случай, что файл не удается удалить, в Windows возбуждается исключение WindowsError.

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

Python copy file (Examples)

In this python tutorial, we will discuss the Python copy file. We will also check:

  • Python copy file to a folder
  • Python copy files from one location to another
  • Python copy file from one directory to another
  • Python copy file to USB
  • Python copy file content to another file
  • Python copy file and rename
  • Python copy file from subfolders to one folder
  • Python copy file to the current directory
  • Python copy file line by line
  • Python copy file overwrite

Let us check on how to copy files in Python with a few examples.

Python shutil.copy()method

The shutil.copy() method in Python is used to copy the files or directories from the source to the destination. The source must represent the file, and the destination may be a file or directory.

Читайте также:  Intel dg33bu драйвера windows 10

This function provides collection and operations on the files it also helps in the copying and removal of files and directories.

Python copy file to folder

Now, we can see how to copy file in python.

  • In this example, I have imported two modules called shutil, and os this module helps in automating the process of copying and removing files and directories.
  • We have to write a path for both source and destination. We have to use shutil.copyfile(src, dst) to copy the file from source to destination. Along with the path, the name of the file with its extension should be written.
  • src = r’C:\Users\Administrator.SHAREPOINTSKY\Desktop\Work\name.txt’ is the source path. name.txt is the filename that I have created with the .txt extension.
  • dst = r’C:\Users\Administrator.SHAREPOINTSKY\Desktop\Newfolder\name.txt’ is the destination path. Here, I have created a folder called Newfolder to copy the file name.txt in the Newfolder.

Python copy files from one location to another

Here, we can see how to copy files from one location to another in Python

  • In this example, I have imported two modules called shutil and os. Here, the shutil module helps in automating the process of coping and removing files and directories.
  • src= r’C:\Newfile\file2.txt’ is the source path. file2.txt is the filename that I have created with the .txt extension.
  • dst = r’D:\file2.txt’ destination path. file2.txt is the filename that I have created with the .txt extension.
  • Here, I have copied the file from C drive to D drive
  • To copy the file from one location to another, we have to use shutil.copyfile(src, dst).

Python copy file from one directory to another

Here, we can see how to copy file from one directory to another in Python.

  • In this example, I have imported modules called shutil and os in Python. The shutil module helps in automating the process of coping and removing files and directories.
  • src = r’C:\Users\Administrator.SHAREPOINTSKY\Desktop\Work\file2.txt’ is the source path. file2.txt is the name of the file with the .txt extension.
  • dst = r’C:\Users\Administrator.SHAREPOINTSKY\Desktop\Newfolder\file2.txt’ is the destination path. file2.txt is the name of the file with the .txt extension.
  • Work and New folder are the two directories.
  • To copy the file from one directory to another, we have to use shutil.copyfile(src, dst).

Python copy file to USB

Here, we can see how to copy a file to USB in Python.

  • In this example, I have imported modules called shutil and os. The shutil module helps in automating the process of coping and removing files and directories.
  • I have used shutil.copy(src, dst) to copy the file to USB.
  • src=r’C:\Users\Administrator.SHAREPOINTSKY\Desktop\Work\name.txt is the path of the file, name.txt is the filename that I have created with the .txt extension.
  • dst=r’D:\lakshmi\name.txt’ is the path of the USB. The name.txt is the filename that I have created with the .txt extension. In this “lakshmi” is the folder name and the filename is name.txt which is copied to “r’D:\lakshmi\name.txt’ “ (which is our USB drive).
  • Along with the path, the name of the file and its extension should be written.

This is how to copy file to USB in Python.

Python copy file content to another file

Now, we can see how to copy file content to another file in Python.

  • In this example, I have imported two modules called os and sys. The sys module provides functions and variables used to manipulate the program.
  • f = open(r’C:\Users\Administrator.SHAREPOINTSKY\Desktop\Work\employee.txt’,”r”) is the source path. The employee.txt is the file name that I have created with the .txt extension.
  • copy = open(r’C:\Users\Administrator.SHAREPOINTSKY\Desktop\Newfolder\employee.txt’,”wt”) is destination path. The employee.txt is the file name that I have created with the .txt extension.
  • line = f.read() reads the specified bytes from the file to another file.
  • copy.write(str(line)) is used to write each line in the file.
  • f.close is used to close the opened file. It is necessary to use a copy.close() while iterating a file in python.

This is how we can copy file content to another file in Python.

Python copy file and rename

Here, we can see how to copy file and rename in Python.

  • In this example, I have imported Python modules called shutil and os.
  • Firstly, we have to copy the file from source to destination and then rename the copied file.
  • src = r’C:\Users\Administrator.SHAREPOINTSKY\Desktop\Work\name.txt’ is the source path. name.txt is the file name that I have created with the .txt extension.
  • dst = r’C:\Users\Administrator.SHAREPOINTSKY\Desktop\Newfolder\name.txt’ is the destination path. The name.txt is the file name that I have created with the .txt extension.
  • os.rename is used to rename the folder name. To rename the file, I have used os.rename(r’C:\Users\Administrator.SHAREPOINTSKY\Desktop\Work\name.txt’,r’C:\Users\Administrator.SHAREPOINTSKY\Desktop\Newfolder\details.txt’)
  • shutil.copyfile(src, dst) is used to copy the file from source to destination.
  • The name.txt file name is now renamed by the name called details.txt.

The above code, we can use to copy file and rename in Python.

Python copy file from subfolders to one folder

Here, we will see how to copy file from subfolder to one folder in Python.

  • In this example, I have used two modules called shutil, and os. The shutil module helps in automating the process of coping and removing files and directories.
  • The os module includes many functionalities like interacting with the filesystem.
  • src= r’C:\Users\Administrator.SHAREPOINTSKY\Desktop\Work\office\employee.txt’. is the source path, employee.txt is the filename that I have created with the .txt extension.
  • dst = r’C:\Users\Administrator.SHAREPOINTSKY\Desktop\Newfolder\employee.txt‘. is the destination path. The employee.txt is the filename that I have created with the .txt extension.
  • The office is a subfolder and a New folder is another folder in this example.
Читайте также:  Repair grub after installing windows

This is how to copy file from subfolders to one folder in Python.

Python copy file to the current directory

Now, we can see how to copy file to the current directory in Python.

  • In this example, I have used two modules called shutil, and os. The shutil module helps in automating the process of coping and removing files and directories.
  • The os module includes many functionalities like interacting with the filesystem.
  • src = r’C:\Users\Administrator.SHAREPOINTSKY\Desktop\Work\office\employee.txt’ is the source path. employee.txt is the filename that I have created with the .txt extension.
  • dst = r’C:\Users\Administrator.SHAREPOINTSKY\Desktop\Work\employee.txt’ is the destination path. The employee.txt is the filename that I have created with the .txt extension.
  • Work is the current directory in this example.
  • shutil.copyfile(src, dst) is used to copy the file to the current directory.

This is how to copy file to the current directory in Python.

Python copy file line by line

Now, we can see how to copy file line by line in python.

  • In this example, I have imported two modules called os and sys. The sys module provides functions and variables used to manipulate the program.
  • src = open(r’C:\Users\Administrator.SHAREPOINTSKY\Desktop\Work\employee.txt’,”r”) is the source path. The employee.txt is the filename that I have created with the .txt extension.
  • dst = open(r’C:\Users\Administrator.SHAREPOINTSKY\Desktop\Newfolder\employee.txt’,”wt”) is the destination path. The employee.txt is the filename that I have created with the .txt extension.
  • I have used the iterating function to iterate the file object in the range i = 1 and i Python copy file overwrite

Here, we can see how to copyfile and overwrite in python.

  • In this example, I have imported a module called shutil, and os. The shutil module helps in automating the process of coping and removing files and directories.
  • src = r’C:\Users\Administrator.SHAREPOINTSKY\Desktop\Work\employee.txt’. is the path of the source file. The employee.txt is the filename that I have created with the .txt extension.
  • dst = r’C:\Users\Administrator.SHAREPOINTSKY\Desktop\Work\employee.txt’. is the path of the destination file. The employee.txt is the filename that I have created with the .txt extension.
  • shutil.move(src, dst) is used to copy the file from source to destination.
  • If the file is already present it will be moved to another directory, and then the file is overwritten. The shutil.move(src, dst) is used to move the file and overwrite. The work is the folder name.

Python check if a file is open

Here, we will see how to check the file is present or not by using os.system in python.

  • In this example, I have imported a module called os.path. This module is a path module for the operating system. It is used for the local paths.
  • The if os.path.isfile() is a method used to check whether the given files are present or not. The ‘kavita.txt’ is the filename. The else condition is used here to check if the condition is true, then it returns the file which is present else it will return the file not present.

As the file is present, It returns a file is present in the output. You can refer to the below screenshot for the output.

This is how to check if a file is open in Python.

Python check if a file is already opened

Here, we can see how to check if a file is already opened in python

In this example, I have opened a file called document using “wb+” mode which is used to read and write the file, as the file is created and it is already present it gives the output as the file is already opened. The ‘document’ is the file name.

To check the file is already opened, I have used print(“file is already opened”). You can refer to the below screenshot for the output.

This is how to check if a file is already opened in Python.

Python check if a file exists

Now, we can see how to check if a file exists in python.

  • In this example, I have imported a module called os.path. This module is a path module for the operating system, it is used for the local paths.
  • The path.exists() is a method that returns true if the file exists otherwise it returns false. Here, ‘document’ is the file name.

To check whether the file exists or not, I have used print(path.exists(‘document’)). The below screenshot shows the output.

Python check if a file exists

The above coder, we can use to check if a file exists in Python.

You may like the following Python tutorials:

In this Python tutorial, we have learned about the Copy file in Python. Also, We covered these below topics:

  • Python copy file to a folder
  • Python copy files from one location to another
  • Python copy file from one directory to another
  • Python copy file to USB
  • Python copy file content to another file
  • Python copy file and rename
  • Python copy file from subfolders to one folder
  • Python copy file to the current directory
  • Python copy file line by line
  • Python copy file overwrite

Entrepreneur, Founder, Author, Blogger, Trainer, and more. Check out my profile.

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