Hướng Dẫn When a piece of data is read from a file it is copied from the file into the program Python? - Lớp.VN

Mẹo về When a piece of data is read from a file it is copied from the file into the program Python? 2022

Cao Thị Phương Thảo đang tìm kiếm từ khóa When a piece of data is read from a file it is copied from the file into the program Python? được Update vào lúc : 2022-09-07 05:36:03 . Với phương châm chia sẻ Kinh Nghiệm Hướng dẫn trong nội dung bài viết một cách Chi Tiết 2022. Nếu sau khi tham khảo nội dung bài viết vẫn ko hiểu thì hoàn toàn có thể lại phản hồi ở cuối bài để Mình lý giải và hướng dẫn lại nha.

In this short guide, you’ll see how to copy a file, from one thư mục to another, using Python.

Nội dung chính
    Step 1: Capture the original pathStep 2: Capture the target pathStep 3: Copy the file in Python using shutil.copyfileUnderstanding how to copy files in Python using shutil libraryIntroductionshutil.copyshutil.copyfileshutil.copy2shutil.copyfileobjFinal ThoughtsWhat happens when a piece of data is written to a file?How do I transfer data from one file to another in Python?How read data file in Python?What is the process of retrieving data from a file called?

To start, here is a template that you may use to copy a file in Python using shutil.copyfile:

import shutil original = r'original path where the file is currently storedfile name.file extension' target = r'target path where the file will be copiedfile name.file extension' shutil.copyfile(original, target)

Let’s now see the steps to apply the above template in practice.

Step 1: Capture the original path

To begin, capture the path where your file is currently stored.

For example, let’s suppose that a CSV file is stored in a thư mục called Test_1:

C:UsersRonDesktopTest_1products.csv

Where the CSV file name is ‘products‘ and the file extension is csv.

Step 2: Capture the target path

Next, capture the target path where you’d like to copy the file.

For our example, the file will be copied into a thư mục called Test_2:

C:UsersRonDesktopTest_2products.csv

Step 3: Copy the file in Python using shutil.copyfile

For the final step, use the following template to copy your file:

import shutil original = r'original path where the file is currently storedfile name.file extension' target = r'target path where the file will be copiedfile name.file extension' shutil.copyfile(original, target)

Make sure to place the ‘r‘ character before your paths to avoid the following error:

SyntaxError: (unicode error) ‘unicodeescape’ codec can’t decode bytes in position 2-3: truncated UXXXXXXXX escape

In the context of our example, the complete code would look like this:

import shutil original = r'C:UsersRonDesktopTest_1products.csv' target = r'C:UsersRonDesktopTest_2products.csv' shutil.copyfile(original, target)

If you run the code in Python (adjusted to your paths), you’ll see that the ‘products‘ CSV file would be copied into the Test_2 thư mục.

Alternatively, you may copy a file with a new name.

For instance, let’s copy the original CSV file (with the file name of ‘products‘) to the new location with a new file name (‘new_products‘):

import shutil original = r'C:UsersRonDesktopTest_1products.csv' target = r'C:UsersRonDesktopTest_2new_products.csv' shutil.copyfile(original, target)

The new file name (called ‘new_products‘) would then be copied in the target location (the Test_2 thư mục).

The same principles would apply for other file types. For instance, let’s suppose that a JPG file called ‘image‘ is stored in the Test_1 thư mục.

The following code can then be used to copy the image to the Test_2 thư mục:

import shutil original = r'C:UsersRonDesktopTest_1image.jpg' target = r'C:UsersRonDesktopTest_2image.jpg' shutil.copyfile(original, target)

The JPG file should now appear in the Test_2 thư mục.

Understanding how to copy files in Python using shutil library

Photo by Volodymyr Hryshchenko on Unsplash

Introduction

Copying files programmatically, is one of the most common tasks in day-to-day software development. In today’s short guide we will explore a few different ways for copying files in Python using a library called shutil.

The shutil module is part of the Python’s Standard Library and offers a wide range of high level file operations. Now with respect to file copying, the library offers numerous methods that can be used depending on whether you want to copy metadata or file permissions and whether the desired destination will be a directory.

In this article, we will discuss about all available methods for doing so, namely

    shutil.copyshutil.copyfileshutil.copy2shutil.copyfileobj

At the end of the guide you can find a table that summarises the features of each individual methods mentioned above.

shutil.copy

shutil.copy() method is used to copy specified source (without the metadata) to the destination file or directory and it will return the path to the newly created file. The src can either be a path-like object or a string.

shutil.copy(src, dst, *, follow_symlinks=True)
    Preserves file permissionsDestination can be a directoryDoes not copy metadataDoes not work with File objects

Example

import shutil# Copy file example.txt into a new file called example_copy.txt
shutil.copy('example.txt', 'example_copy.txt')# Copy file example.txt into directory test/
shutil.copy('example.txt', 'test/')

shutil.copyfile

The shutil.copyfile() method is used to copy the source file (without the metadata) to the specified destination file. Again, the src can either be a path-like object or a string.

shutil.copyfile(src, dst, *, follow_symlinks=True)
    Does not preserve file permissionsDestination cannot be a directoryDoes not copy metadataDoes not work with File objects

Example

import shutil# Copy file example.txt into a new file called example_copy.txt
shutil.copyfile('source.txt', 'destination.txt')

shutil.copy2

The shutil.copy2() method is identical to shutil.copy() except that copy2() attempts to preserve file metadata as well.

shutil.copy2(src, dst, *, follow_symlinks=True)
    Preserves file permissionsDestination can be a directoryCopies metadataDoes not work with File objects

Example

import shutil# Copy file example.txt into a new file called example_copy.txt
shutil.copy2('example.txt', 'example_copy.txt')# Copy file example.txt into directory test/
shutil.copy2('example.txt', 'test/')

shutil.copyfileobj

Now if you have to work with File Objects then shutil.copyfileobj is the way to go. Essentially, the method will copy the contents of the source file object to the specified destination file-like object. You can also set the length that corresponds to the buffer size used to copy the contents.

shutil.copyfileobj(fsrc, fdst[, length])
    Does not preserve file permissionsDestination cannot be a directoryDoes not copy metadataCan work with File objects

Example

import shutilsource_file = open('example.txt', 'rb')
dest_file = open('example_copy.txt', 'wb')

shutil.copyfileobj(source_file, dest_file)

Final Thoughts

In today’s short guide we explore a few different ways for programmatically copying files using Python. More precisely, we introduced a few relevant methods offered by shutil module that comes as part of the Standard Library of the language.

Depending on whether you want to copy file permissions, metadata and whether you want to copy a file to a directory (or even use a method which in accepts file objects) you need to choose the one that will do the trick for your specific use-case.

The table below summarises the capabilities of each of the methods discussed in this article. Note that the only method that accepts File Objects is shutil.copyfileobj.

+--------------------+----------------+--------------+-------------+
| Method | Preserves File | Destination | Copies |
| | Permissions | can be a dir | Metadata |
+--------------------+----------------+--------------+-------------+
| shutil.copy | ✔ | ✔ | ✗ |
| shutil.copyfile | ✗ | ✗ | ✗ |
| shutil.copy2 | ✔ | ✔ | ✔ |
| shutil.copyfileobj | ✗ | ✗ | ✗ |
+--------------------+----------------+--------------+-------------+

Become a thành viên and read every story on Medium. Your membership fee directly supports me and other writers you read. You’ll also get full access to every story on Medium.

What happens when a piece of data is written to a file?

Which of the following describes what happens when a piece of data is written to a file? The data is copied from a variable in RAM to a file.

How do I transfer data from one file to another in Python?

Python Program to Copy One File to Another File. Open one file called test. txt in read mode.. Open another file out. txt in write mode.. Read each line from the input file and write it into the output file..

How read data file in Python?

To read a text file in Python, you follow these steps: First, open a text file for reading by using the open() function. Second, read text from the text file using the file read() , readline() , or readlines() method of the file object. Third, close the file using the file close() method.

What is the process of retrieving data from a file called?

What is the process of retrieving data from a file? Known as reading data from the file. Tải thêm tài liệu liên quan đến nội dung bài viết When a piece of data is read from a file it is copied from the file into the program Python?

Video When a piece of data is read from a file it is copied from the file into the program Python? ?

Bạn vừa Read Post Với Một số hướng dẫn một cách rõ ràng hơn về Clip When a piece of data is read from a file it is copied from the file into the program Python? tiên tiến nhất

Chia Sẻ Link Cập nhật When a piece of data is read from a file it is copied from the file into the program Python? miễn phí

Bạn đang tìm một số trong những Share Link Down When a piece of data is read from a file it is copied from the file into the program Python? miễn phí.

Giải đáp thắc mắc về When a piece of data is read from a file it is copied from the file into the program Python?

Nếu sau khi đọc nội dung bài viết When a piece of data is read from a file it is copied from the file into the program Python? vẫn chưa hiểu thì hoàn toàn có thể lại Comment ở cuối bài để Tác giả lý giải và hướng dẫn lại nha #piece #data #read #file #copied #file #program #Python - 2022-09-07 05:36:03
إرسال تعليق (0)
أحدث أقدم