Hướng dẫn how do you copy a file in python terminal? - làm thế nào để bạn sao chép một tập tin trong thiết bị đầu cuối python?
Python đi kèm với nhiều mô -đun ngoài hộp (như HĐH, quy trình con và SHOWIL) để hỗ trợ các hoạt động I/O của tệp. Và trong bài đăng này, bạn sẽ có thể thấy một số cách độc đáo để sao chép một tệp trong Python. Vì vậy, hãy để bắt đầu tìm hiểu chín phương pháp khác nhau để thực hiện hoạt động tệp Python Copy.some unique ways to copy a file in Python. So, let’s get started to learn the nine different methods to do Python copy file operation. Show
Trước khi bạn bắt đầu, bạn phải hiểu tại sao điều quan trọng là phải biết phương thức tập tin nào trong Python là tốt nhất cho bạn. Đó là bởi vì các hoạt động I/O của tập tin rất chuyên sâu và thường dẫn đến tắc nghẽn. Đó là lý do tại sao bạn nên chọn cách tiếp cận tốt nhất có thể theo thiết kế ứng dụng của bạn. Một số chương trình sử dụng các tài nguyên được chia sẻ muốn sao chép một tệp trong chế độ chặn trong khi một số chương trình có thể muốn làm điều đó một cách không đồng bộ. Ví dụ: sử dụng một luồng để sao chép một tệp hoặc bắt đầu một quy trình riêng để thực hiện. Một điểm khác để xem xét là tính di động của nền tảng. Điều đó có nghĩa là bạn nên biết HĐH Target (Windows/Linux/Mac OS X, v.v.) bất cứ nơi nào bạn sẽ chạy chương trình. Với mô -đun Shutil, bạn có thể tự động sao chép cả tệp và thư mục. Mô -đun này theo một thiết kế tối ưu hóa. Nó giúp bạn không thực hiện các hoạt động tốn nhiều thời gian như mở, đọc, viết và đóng tệp khi không có nhu cầu xử lý thực sự. Nó có đầy đủ các chức năng và phương thức tiện ích có thể cho phép bạn thực hiện các tác vụ như sao chép, di chuyển hoặc xóa các tệp và thư mục. Dưới đây là chín phương pháp để chứng minh cách sao chép một tệp trong Python?nine methods to demonstrate “How to copy a file in Python?”.
1. Phương thức SOWLIL COPYFILE ()Phương thức này chỉ sao chép nội dung của nguồn đến đích nếu mục tiêu có thể ghi. Nếu bạn không có quyền phù hợp, thì nó sẽ tăng ioerror.IOError. Nó hoạt động bằng cách mở tệp đầu vào để đọc trong khi bỏ qua loại tệp của nó. Tiếp theo, nó không đối xử với các tệp đặc biệt khác nhau và won đã tạo ra bản sao của họ. Phương thức copyFile () sử dụng hàm cấp thấp hơn copyFiLeobj () bên dưới. Nó lấy tên tệp làm đối số, mở chúng và chuyển xử lý tệp cho copyfileObj (). Có một đối số thứ ba tùy chọn trong phương pháp này mà bạn có thể sử dụng để chỉ định độ dài bộ đệm. Sau đó, nó sẽ mở tệp để đọc trong các khối của kích thước bộ đệm được chỉ định. Tuy nhiên, hành vi mặc định là đọc toàn bộ tệp trong một lần.copyfile() method makes use of lower-level function copyfileobj() underneath. It takes file names as arguments, opens them and passes file handles to copyfileobj(). There is one optional third argument in this method which you can use to specify the buffer length. It’ll then open the file for reading in chunks of the specified buffer size. However, the default behavior is to read the entire file in one go. copyfile(source_file, destination_file) Sau đây là những điểm cần biết về phương thức copyFile ().copyfile() method.
# Python Copy File - Sample Code from shutil import copyfile from sys import exit source = input("Enter source file with full path: ") target = input("Enter target file with full path: ") # adding exception handling try: copyfile(source, target) except IOError as e: print("Unable to copy file. %s" % e) exit(1) except: print("Unexpected error:", sys.exc_info()) exit(1) print("\nFile copy done!\n") while True: print("Do you like to print the file ? (y/n): ") check = input() if check == 'n': break elif check == 'y': file = open(target, "r") print("\nHere follows the file content:\n") print(file.read()) file.close() print() break else: continue Trở lại đầu trang 2. Phương thức SOWLIL SOPY ()copyfile(source_file, [destination_file or dest_dir]) Phương thức Copy () có chức năng giống như lệnh CP CP trong Unix. Nó có nghĩa là nếu mục tiêu là một thư mục, thì nó sẽ tạo một tệp mới bên trong nó với cùng tên (basename) là tệp nguồn. Ngoài ra, phương pháp này sẽ đồng bộ các quyền của tệp đích với nguồn sau khi sao chép nội dung của nó. & NBSP; copy() method functions like the “cp” command in Unix. It means if the target is a folder, then it’ll create a new file inside it with the same name (basename) as the source file. Also, this method will sync the permissions of the target file with the source after copying its content. It too throws the SameFileError if you are copying the same file. import os import shutil source = 'current/test/test.py' target = '/prod/new' assert not os.path.isabs(source) target = os.path.join(target, os.path.dirname(source)) # create the folders if not already exists os.makedirs(target) # adding exception handling try: shutil.copy(source, target) except IOError as e: print("Unable to copy file. %s" % e) except: print("Unexpected error:", sys.exc_info()) Copy () vs copyFile () -
Trở lại đầu trang 2. Phương thức SOWLIL SOPY ()Phương thức Copy () có chức năng giống như lệnh CP CP trong Unix. Nó có nghĩa là nếu mục tiêu là một thư mục, thì nó sẽ tạo một tệp mới bên trong nó với cùng tên (basename) là tệp nguồn. Ngoài ra, phương pháp này sẽ đồng bộ các quyền của tệp đích với nguồn sau khi sao chép nội dung của nó. & NBSP;copyfileobj(). It assumes an optional argument (the buffer size) which you can use to supply the buffer length. It is the number of bytes kept in memory during the copy process. The default size that system use is 16KB. from shutil import copyfileobj status = False if isinstance(target, string_types): target = open(target, 'wb') status = True try: copyfileobj(self.stream, target, buffer_size) finally: if status: target.close() Trở lại đầu trang 2. Phương thức SOWLIL SOPY ()Tuy nhiên, phương thức Copy2 () có chức năng như Copy (). Nhưng nó cũng có thời gian truy cập và sửa đổi được thêm vào dữ liệu meta trong khi sao chép dữ liệu. Sao chép cùng một tệp sẽ dẫn đến giống nhau.copy2() method functions like the copy(). But it also gets the access and modification times added in the meta-data while copying the data. Copying the same file would result in SameFileError. from shutil import * import os import time from os.path import basename def displayFileStats(filename): file_stats = os.stat(basename(filename)) print('\tMode :', file_stats.st_mode) print('\tCreated :', time.ctime(file_stats.st_ctime)) print('\tAccessed:', time.ctime(file_stats.st_atime)) print('\tModified:', time.ctime(file_stats.st_mtime)) os.mkdir('test') print('SOURCE:') displayFileStats(__file__) copy2(__file__, 'testfile') print('TARGET:') displayFileStats(os.path.realpath(os.getcwd() + './test/testfile')) Copy () vs copy2 ()
copymode () vs copystat ()shutil.copymode() copymode(source, target, *, follow_symlinks=True)
shutil.copystat() copystat(source, target, *, follow_symlinks=True)
Trở lại đầu trang 5. Phương thức os popen ()Phương pháp này tạo ra một đường ống đến hoặc từ lệnh. Nó trả về một đối tượng tệp mở kết nối với một đường ống. Bạn có thể sử dụng nó để đọc hoặc viết theo chế độ tệp, tức là, ‘r, (mặc định) hoặc‘ w. os.popen(command[, mode[, bufsize]])
Cho hệ điều hành Windows.import os os.popen('copy 1.txt.py 2.txt.py') Cho Linux OS.# Python Copy File - Sample Code from shutil import copyfile from sys import exit source = input("Enter source file with full path: ") target = input("Enter target file with full path: ") # adding exception handling try: copyfile(source, target) except IOError as e: print("Unable to copy file. %s" % e) exit(1) except: print("Unexpected error:", sys.exc_info()) exit(1) print("\nFile copy done!\n") while True: print("Do you like to print the file ? (y/n): ") check = input() if check == 'n': break elif check == 'y': file = open(target, "r") print("\nHere follows the file content:\n") print(file.read()) file.close() print() break else: continue0 Trở lại đầu trang 5. Phương thức os popen ()Phương pháp này tạo ra một đường ống đến hoặc từ lệnh. Nó trả về một đối tượng tệp mở kết nối với một đường ống. Bạn có thể sử dụng nó để đọc hoặc viết theo chế độ tệp, tức là, ‘r, (mặc định) hoặc‘ w.system() method allows you to instantly execute any OS command or a script in the subshell. Chế độ - Nó có thể là ‘R, (mặc định) hoặc‘ W.system() call. Internally, this method calls the standard C library function. BUFSIZE - Nếu giá trị của nó là 0, thì sẽ không có bộ đệm nào xảy ra. Nếu bufsize là 1, thì bộ đệm dòng sẽ diễn ra trong khi truy cập vào tệp. Nếu bạn cung cấp một giá trị lớn hơn 1, thì bộ đệm sẽ xảy ra với kích thước bộ đệm được chỉ định. Tuy nhiên, đối với một giá trị âm, hệ thống sẽ giả sử kích thước bộ đệm mặc định. Cho hệ điều hành Windows.# Python Copy File - Sample Code from shutil import copyfile from sys import exit source = input("Enter source file with full path: ") target = input("Enter target file with full path: ") # adding exception handling try: copyfile(source, target) except IOError as e: print("Unable to copy file. %s" % e) exit(1) except: print("Unexpected error:", sys.exc_info()) exit(1) print("\nFile copy done!\n") while True: print("Do you like to print the file ? (y/n): ") check = input() if check == 'n': break elif check == 'y': file = open(target, "r") print("\nHere follows the file content:\n") print(file.read()) file.close() print() break else: continue1 Cho Linux OS.# Python Copy File - Sample Code from shutil import copyfile from sys import exit source = input("Enter source file with full path: ") target = input("Enter target file with full path: ") # adding exception handling try: copyfile(source, target) except IOError as e: print("Unable to copy file. %s" % e) exit(1) except: print("Unexpected error:", sys.exc_info()) exit(1) print("\nFile copy done!\n") while True: print("Do you like to print the file ? (y/n): ") check = input() if check == 'n': break elif check == 'y': file = open(target, "r") print("\nHere follows the file content:\n") print(file.read()) file.close() print() break else: continue2 Trở lại đầu trang 5. Phương thức os popen ()Phương pháp này tạo ra một đường ống đến hoặc từ lệnh. Nó trả về một đối tượng tệp mở kết nối với một đường ống. Bạn có thể sử dụng nó để đọc hoặc viết theo chế độ tệp, tức là, ‘r, (mặc định) hoặc‘ w. Chế độ - Nó có thể là ‘R, (mặc định) hoặc‘ W. # Python Copy File - Sample Code from shutil import copyfile from sys import exit source = input("Enter source file with full path: ") target = input("Enter target file with full path: ") # adding exception handling try: copyfile(source, target) except IOError as e: print("Unable to copy file. %s" % e) exit(1) except: print("Unexpected error:", sys.exc_info()) exit(1) print("\nFile copy done!\n") while True: print("Do you like to print the file ? (y/n): ") check = input() if check == 'n': break elif check == 'y': file = open(target, "r") print("\nHere follows the file content:\n") print(file.read()) file.close() print() break else: continue3 Trở lại đầu trang 5. Phương thức os popen ()Phương pháp này tạo ra một đường ống đến hoặc từ lệnh. Nó trả về một đối tượng tệp mở kết nối với một đường ống. Bạn có thể sử dụng nó để đọc hoặc viết theo chế độ tệp, tức là, ‘r, (mặc định) hoặc‘ w.input/output/error pipes, and retrieve the return values. Chế độ - Nó có thể là ‘R, (mặc định) hoặc‘ W.os.system, os.spawn*, os.popen*, popen2.*. BUFSIZE - Nếu giá trị của nó là 0, thì sẽ không có bộ đệm nào xảy ra. Nếu bufsize là 1, thì bộ đệm dòng sẽ diễn ra trong khi truy cập vào tệp. Nếu bạn cung cấp một giá trị lớn hơn 1, thì bộ đệm sẽ xảy ra với kích thước bộ đệm được chỉ định. Tuy nhiên, đối với một giá trị âm, hệ thống sẽ giả sử kích thước bộ đệm mặc định.call() method to invoke system commands to execute user tasks. # Python Copy File - Sample Code from shutil import copyfile from sys import exit source = input("Enter source file with full path: ") target = input("Enter target file with full path: ") # adding exception handling try: copyfile(source, target) except IOError as e: print("Unable to copy file. %s" % e) exit(1) except: print("Unexpected error:", sys.exc_info()) exit(1) print("\nFile copy done!\n") while True: print("Do you like to print the file ? (y/n): ") check = input() if check == 'n': break elif check == 'y': file = open(target, "r") print("\nHere follows the file content:\n") print(file.read()) file.close() print() break else: continue4 Trở lại đầu trang 5. Phương thức os popen ()Phương pháp này tạo ra một đường ống đến hoặc từ lệnh. Nó trả về một đối tượng tệp mở kết nối với một đường ống. Bạn có thể sử dụng nó để đọc hoặc viết theo chế độ tệp, tức là, ‘r, (mặc định) hoặc‘ w.check_output() method, you can run an external command or a program and capture its output. It also supports pipes. # Python Copy File - Sample Code from shutil import copyfile from sys import exit source = input("Enter source file with full path: ") target = input("Enter target file with full path: ") # adding exception handling try: copyfile(source, target) except IOError as e: print("Unable to copy file. %s" % e) exit(1) except: print("Unexpected error:", sys.exc_info()) exit(1) print("\nFile copy done!\n") while True: print("Do you like to print the file ? (y/n): ") check = input() if check == 'n': break elif check == 'y': file = open(target, "r") print("\nHere follows the file content:\n") print(file.read()) file.close() print() break else: continue5 Trở lại đầu trang 5. Phương thức os popen ()Phương pháp này tạo ra một đường ống đến hoặc từ lệnh. Nó trả về một đối tượng tệp mở kết nối với một đường ống. Bạn có thể sử dụng nó để đọc hoặc viết theo chế độ tệp, tức là, ‘r, (mặc định) hoặc‘ w. Chế độ - Nó có thể là ‘R, (mặc định) hoặc‘ W. BUFSIZE - Nếu giá trị của nó là 0, thì sẽ không có bộ đệm nào xảy ra. Nếu bufsize là 1, thì bộ đệm dòng sẽ diễn ra trong khi truy cập vào tệp. Nếu bạn cung cấp một giá trị lớn hơn 1, thì bộ đệm sẽ xảy ra với kích thước bộ đệm được chỉ định. Tuy nhiên, đối với một giá trị âm, hệ thống sẽ giả sử kích thước bộ đệm mặc định.Facebook and Twitter. Best, Cho hệ điều hành Windows. |