Hướng dẫn split big file into smaller parts python - chia tệp lớn thành các phần nhỏ hơn python
Dưới đây là tập lệnh Python bạn có thể sử dụng để phân tách các tệp lớn bằng 0: Show
Bạn có thể gọi nó bên ngoài:
Bạn cũng có thể nhập 0 và chạy trực tiếp trong chương trình của mình.Vấn đề với phương pháp này là cách sử dụng bộ nhớ cao: 0 tạo ra một ngã ba với dấu chân bộ nhớ có cùng kích thước với quy trình của bạn và nếu bộ nhớ quy trình của bạn đã nặng, nó sẽ tăng gấp đôi nó trong thời gian nó chạy. Điều tương tự với 3.Dưới đây là một cách Python thuần túy khác, mặc dù tôi chưa thử nghiệm nó trên các tệp khổng lồ, nó sẽ chậm hơn nhưng hãy nghiêng về bộ nhớ:
Dưới đây là một ví dụ khác bằng cách sử dụng 4:
Ví dụ Readlines trình bày cách tạo dữ liệu của bạn để truyền các khối để hoạt động mà mong đợi các khối. Thật không may, các lần đọc mở ra toàn bộ tệp trong bộ nhớ, tốt hơn là sử dụng ví dụ đầu đọc cho hiệu suất. Mặc dù nếu bạn có thể dễ dàng phù hợp với những gì bạn cần vào bộ nhớ và cần xử lý nó trong các khối này thì đủ. Chia và tham gia các tệpGiống như hầu hết trẻ em, tôi dành nhiều thời gian trên internet. Theo như tôi có thể nói, đó là điều cần làm trong những ngày này. Trong số thế hệ mới nhất này, các chuyên viên máy tính và bậc thầy dường như được giữ với cùng một loại lòng tự trọng mà các ngôi sao nhạc rock từng là của tôi. Khi những đứa trẻ biến mất vào phòng của chúng, rất có thể chúng đang hack trên máy tính, không thành thạo các đoạn riff guitar. Nó có lẽ khỏe mạnh hơn một số trò chơi của giới trẻ sai lầm của riêng tôi, nhưng đó là một chủ đề cho một loại sách khác. Nhưng nếu bạn có trẻ em và máy tính tuổi teen, hoặc biết ai đó, bạn có thể biết rằng đó không phải là một ý tưởng tồi để giữ các tab về những gì những đứa trẻ đó làm trên web. Nhập từ bốn chữ cái yêu thích của bạn vào hầu hết mọi công cụ tìm kiếm web và bạn sẽ hiểu được mối quan tâm-đó là thứ tốt hơn nhiều so với tôi có thể nhận được trong suốt sự nghiệp tuổi teen của mình. Để vượt qua vấn đề, chỉ có một vài máy trong nhà tôi có nguồn cấp dữ liệu internet. Bây giờ, trong khi họ trên một trong những máy này, những đứa trẻ của tôi tải xuống rất nhiều trò chơi. Tuy nhiên, để tránh lây nhiễm các máy tính rất quan trọng của chúng tôi với virus từ các trò chơi miền công cộng, những đứa trẻ của tôi thường phải tải xuống các trò chơi trên máy tính có nguồn cấp dữ liệu internet và chuyển chúng vào máy tính của riêng chúng để cài đặt. Vấn đề là các tập tin trò chơi không nhỏ; Chúng thường quá lớn để phù hợp với một đĩa mềm (và ghi đĩa CD sẽ lấy đi thời gian chơi trò chơi có giá trị). Nếu tất cả các máy trong nhà tôi chạy Linux, đây sẽ là một điều không phát hành. Có các chương trình dòng lệnh tiêu chuẩn trên UNIX để cắt một tệp thành các mảnh đủ nhỏ để phù hợp với đĩa mềm (chia) và các chương trình khác để đặt các mảnh lại với nhau để tạo lại tệp gốc (CAT). Bởi vì chúng tôi có tất cả các loại máy khác nhau trong nhà, chúng tôi cần một giải pháp di động hơn.split), and others for putting the pieces back together to recreate the original file (cat). Because we have all sorts of different machines in the house, though, we needed a more portable solution. Tách các tập tin một cách ngẫu nhiênVì tất cả các máy tính trong nhà tôi chạy Python, một kịch bản Python di động đơn giản đã đến giải cứu. Chương trình Python trong ví dụ 4-1 phân phối một nội dung tệp trong một tập hợp các tệp một phần và lưu trữ các tệp một phần đó trong một thư mục. Ví dụ & nbsp; 4-1. & Nbsp; pp2e \ System \ filetools #!/usr/bin/python ######################################################### # split a file into a set of portions; join.py puts them # back together; this is a customizable version of the # standard unix split command-line utility; because it # is written in Python, it also works on Windows and can # be easily tweaked; because it exports a function, it # can also be imported and reused in other applications; ######################################################### import sys, os kilobytes = 1024 megabytes = kilobytes * 1000 chunksize = int(1.4 * megabytes) # default: roughly a floppy def split(fromfile, todir, chunksize=chunksize): if not os.path.exists(todir): # caller handles errors os.mkdir(todir) # make dir, read/write parts else: for fname in os.listdir(todir): # delete any existing files os.remove(os.path.join(todir, fname)) partnum = 0 input = open(fromfile, 'rb') # use binary mode on Windows while 1: # eof=empty string from read chunk = input.read(chunksize) # get next part <= chunksize if not chunk: break partnum = partnum+1 filename = os.path.join(todir, ('part%04d' % partnum)) fileobj = open(filename, 'wb') fileobj.write(chunk) fileobj.close() # or simply open( ).write( ) input.close( ) assert partnum <= 9999 # join sort fails if 5 digits return partnum if __name__ == '__main__': if len(sys.argv) == 2 and sys.argv[1] == '-help': print 'Use: split.py [file-to-split target-dir [chunksize]]' else: if len(sys.argv) < 3: interactive = 1 fromfile = raw_input('File to be split? ') # input if clicked todir = raw_input('Directory to store part files? ') else: interactive = 0 fromfile, todir = sys.argv[1:3] # args in cmdline if len(sys.argv) == 4: chunksize = int(sys.argv[3]) absfrom, absto = map(os.path.abspath, [fromfile, todir]) print 'Splitting', absfrom, 'to', absto, 'by', chunksize try: parts = split(fromfile, todir, chunksize) except: print 'Error during split:' print sys.exc_type, sys.exc_value else: print 'Split finished:', parts, 'parts are in', absto if interactive: raw_input('Press Enter key') # pause if clicked Theo mặc định, tập lệnh này chia tệp đầu vào thành các khối gần bằng kích thước của đĩa mềm - hoàn hảo để di chuyển các tệp lớn giữa các máy bị cô lập bằng điện tử. Quan trọng nhất, bởi vì đây là tất cả mã Python di động, tập lệnh này sẽ chạy trên bất kỳ máy nào, ngay cả những máy không có bộ chia tệp của riêng họ. Tất cả những gì nó yêu cầu là một Python đã cài đặt. Đây là công việc phân tách Python 1.5.2 tự cài đặt có thể thực thi trên Windows: C:\temp> Mỗi trong bốn tệp phần được tạo này đại diện cho một đoạn nhị phân của tệp ____, đủ nhỏ để phù hợp với một cách thoải mái trên một đĩa mềm. Trên thực tế, nếu bạn thêm kích thước của các tệp được tạo bởi lệnh LS, bạn sẽ đưa ra 5.028.339 byte - giống hệt như kích thước tệp gốc. Trước khi chúng ta thấy cách đặt các tệp này lại với nhau một lần nữa, hãy để khám phá một vài điểm của script script.ls command, you’ll come up with 5,028,339 bytes -- exactly the same as the original file’s size. Before we see how to put these files back together again, let’s explore a few of the splitter script’s finer points. Chế độ hoạt độngTập lệnh này được thiết kế để nhập các tham số của nó vào các chế độ tương tác hoặc dòng lệnh; Nó kiểm tra số lượng đối số dòng lệnh để biết nó đang được sử dụng trong chế độ nào. Trong chế độ dòng lệnh, bạn liệt kê tệp sẽ được chia và thư mục đầu ra trên dòng lệnh và có thể tùy ý ghi đè kích thước tệp phần mặc định với đối số dòng lệnh thứ ba.interactive or command-line modes; it checks the number of command-line arguments to know in which mode it is being used. In command-line mode, you list the file to be split and the output directory on the command line, and can optionally override the default part file size with a third command-line argument. Trong chế độ tương tác, tập lệnh yêu cầu một tên tệp và thư mục đầu ra ở cửa sổ bảng điều khiển với 6 và tạm dừng một phím keypress ở cuối trước khi thoát. Chế độ này rất đẹp khi tệp chương trình được bắt đầu bằng cách nhấp vào biểu tượng của nó-trên Windows, các tham số được nhập vào hộp DOS bật lên mà không tự động biến mất. Kịch bản cũng hiển thị các đường dẫn tuyệt đối của các tham số của nó (bằng cách chạy chúng qua 7) vì chúng có thể không rõ ràng ở chế độ tương tác. Chúng tôi sẽ thấy các ví dụ về các chế độ phân chia khác tại nơi làm việc trong một khoảnh khắc.Truy cập tệp nhị phânMã này cẩn thận để mở cả tệp đầu vào và đầu ra ở chế độ nhị phân ( 8, 9), bởi vì nó cần xử lý một cách xác nhận những thứ như thực thi và tệp âm thanh, không chỉ văn bản. Trong Chương 2, chúng tôi đã học được rằng trên Windows, các tệp chế độ văn bản tự động ánh xạ 0 Trình tự cuối dòng thành 1 trên đầu vào và ánh xạ 1 đến 0 trên đầu ra. Đối với dữ liệu nhị phân thực sự, chúng tôi thực sự không muốn bất kỳ ký tự 4 nào trong dữ liệu biến mất khi đọc và chúng tôi không muốn bất kỳ ký tự 4 nào được thêm vào đầu ra. Các tệp chế độ nhị phân triệt tiêu ánh xạ 4 này khi tập lệnh được chạy trên Windows và do đó tránh tham nhũng dữ liệu.Đóng tệp theo cách thủ côngKịch bản này cũng đi ra ngoài để đóng các tệp theo cách thủ công. Ví dụ: fileobj = open(partname, 'wb') fileobj.write(chunk) fileobj.close( ) Như chúng ta cũng đã thấy trong Chương 2, ba dòng này thường có thể được thay thế bằng dòng đơn này: open(partname, 'wb').write(chunk) Hình thức ngắn hơn này dựa trên thực tế là việc triển khai Python hiện tại sẽ tự động đóng các tệp cho bạn khi các đối tượng tệp được thu hồi (nghĩa là, khi chúng được thu thập rác, vì không còn tài liệu tham khảo nào đến đối tượng tệp). Trong dòng này, đối tượng tệp sẽ được thu hồi ngay lập tức, bởi vì kết quả 7 là tạm thời trong một biểu thức và không bao giờ được tham chiếu bởi một tên sống lâu hơn. Tệp 8 tương tự được thu hồi khi hàm 9 thoát ra.Tuy nhiên, khi tôi viết chương này, có một số khả năng hành vi gần gũi tự động này có thể biến mất trong tương lai. [32] Hơn nữa, việc triển khai Python dựa trên JPython Java không đòi lại các đối tượng không được giới thiệu ngay lập tức như Python tiêu chuẩn. Nếu bạn quan tâm đến cổng Java (hoặc một tương lai có thể), tập lệnh của bạn có thể có khả năng tạo nhiều tệp trong một khoảng thời gian ngắn và tập lệnh của bạn có thể chạy trên một máy có giới hạn về số lượng tệp mở cho mỗi chương trình, thì Đóng thủ công. Các cuộc gọi #!/usr/bin/python ######################################################### # split a file into a set of portions; join.py puts them # back together; this is a customizable version of the # standard unix split command-line utility; because it # is written in Python, it also works on Windows and can # be easily tweaked; because it exports a function, it # can also be imported and reused in other applications; ######################################################### import sys, os kilobytes = 1024 megabytes = kilobytes * 1000 chunksize = int(1.4 * megabytes) # default: roughly a floppy def split(fromfile, todir, chunksize=chunksize): if not os.path.exists(todir): # caller handles errors os.mkdir(todir) # make dir, read/write parts else: for fname in os.listdir(todir): # delete any existing files os.remove(os.path.join(todir, fname)) partnum = 0 input = open(fromfile, 'rb') # use binary mode on Windows while 1: # eof=empty string from read chunk = input.read(chunksize) # get next part <= chunksize if not chunk: break partnum = partnum+1 filename = os.path.join(todir, ('part%04d' % partnum)) fileobj = open(filename, 'wb') fileobj.write(chunk) fileobj.close() # or simply open( ).write( ) input.close( ) assert partnum <= 9999 # join sort fails if 5 digits return partnum if __name__ == '__main__': if len(sys.argv) == 2 and sys.argv[1] == '-help': print 'Use: split.py [file-to-split target-dir [chunksize]]' else: if len(sys.argv) < 3: interactive = 1 fromfile = raw_input('File to be split? ') # input if clicked todir = raw_input('Directory to store part files? ') else: interactive = 0 fromfile, todir = sys.argv[1:3] # args in cmdline if len(sys.argv) == 4: chunksize = int(sys.argv[3]) absfrom, absto = map(os.path.abspath, [fromfile, todir]) print 'Splitting', absfrom, 'to', absto, 'by', chunksize try: parts = split(fromfile, todir, chunksize) except: print 'Error during split:' print sys.exc_type, sys.exc_value else: print 'Split finished:', parts, 'parts are in', absto if interactive: raw_input('Press Enter key') # pause if clicked0 trong tập lệnh này chưa bao giờ cần thiết cho các mục đích của tôi, nhưng vì hàm 9 trong mô-đun này được dự định là một công cụ đa năng, nên nó có các trường hợp xấu nhất như vậy.Tham gia các tập tin một cách ngẫu nhiênQuay lại để di chuyển các tập tin lớn quanh nhà. Sau khi tải xuống một tệp chương trình trò chơi lớn, các con tôi thường chạy tập lệnh chia trước đó bằng cách nhấp vào tên của nó trong Windows Explorer và gõ tên tệp. Sau khi chia tách, họ chỉ cần sao chép từng tệp phần lên đĩa mềm của riêng mình, đi bộ trên lầu và tạo lại thư mục đầu ra phân chia trên máy tính đích của họ bằng cách sao chép các tệp ra khỏi floppies. Cuối cùng, tập lệnh trong ví dụ 4-2 được nhấp hoặc chạy để đặt các bộ phận lại với nhau. Ví dụ & nbsp; 4-2. & Nbsp; pp2e \ System \ filetools #!/usr/bin/python ########################################################## # join all part files in a dir created by split.py. # This is roughly like a 'cat fromdir/* > tofile' command # on unix, but is a bit more portable and configurable, # and exports the join operation as a reusable function. # Relies on sort order of file names: must be same length. # Could extend split/join to popup Tkinter file selectors. ########################################################## import os, sys readsize = 1024 def join(fromdir, tofile): output = open(tofile, 'wb') parts = os.listdir(fromdir) parts.sort( ) for filename in parts: filepath = os.path.join(fromdir, filename) fileobj = open(filepath, 'rb') while 1: filebytes = fileobj.read(readsize) if not filebytes: break output.write(filebytes) fileobj.close( ) output.close( ) if __name__ == '__main__': if len(sys.argv) == 2 and sys.argv[1] == '-help': print 'Use: join.py [from-dir-name to-file-name]' else: if len(sys.argv) != 3: interactive = 1 fromdir = raw_input('Directory containing part files? ') tofile = raw_input('Name of file to be recreated? ') else: interactive = 0 fromdir, tofile = sys.argv[1:] absfrom, absto = map(os.path.abspath, [fromdir, tofile]) print 'Joining', absfrom, 'to make', absto try: join(fromdir, tofile) except: print 'Error joining files:' print sys.exc_type, sys.exc_value else: print 'Join complete: see', absto if interactive: raw_input('Press Enter key') # pause if clicked Sau khi chạy tập lệnh #!/usr/bin/python ######################################################### # split a file into a set of portions; join.py puts them # back together; this is a customizable version of the # standard unix split command-line utility; because it # is written in Python, it also works on Windows and can # be easily tweaked; because it exports a function, it # can also be imported and reused in other applications; ######################################################### import sys, os kilobytes = 1024 megabytes = kilobytes * 1000 chunksize = int(1.4 * megabytes) # default: roughly a floppy def split(fromfile, todir, chunksize=chunksize): if not os.path.exists(todir): # caller handles errors os.mkdir(todir) # make dir, read/write parts else: for fname in os.listdir(todir): # delete any existing files os.remove(os.path.join(todir, fname)) partnum = 0 input = open(fromfile, 'rb') # use binary mode on Windows while 1: # eof=empty string from read chunk = input.read(chunksize) # get next part <= chunksize if not chunk: break partnum = partnum+1 filename = os.path.join(todir, ('part%04d' % partnum)) fileobj = open(filename, 'wb') fileobj.write(chunk) fileobj.close() # or simply open( ).write( ) input.close( ) assert partnum <= 9999 # join sort fails if 5 digits return partnum if __name__ == '__main__': if len(sys.argv) == 2 and sys.argv[1] == '-help': print 'Use: split.py [file-to-split target-dir [chunksize]]' else: if len(sys.argv) < 3: interactive = 1 fromfile = raw_input('File to be split? ') # input if clicked todir = raw_input('Directory to store part files? ') else: interactive = 0 fromfile, todir = sys.argv[1:3] # args in cmdline if len(sys.argv) == 4: chunksize = int(sys.argv[3]) absfrom, absto = map(os.path.abspath, [fromfile, todir]) print 'Splitting', absfrom, 'to', absto, 'by', chunksize try: parts = split(fromfile, todir, chunksize) except: print 'Error during split:' print sys.exc_type, sys.exc_value else: print 'Split finished:', parts, 'parts are in', absto if interactive: raw_input('Press Enter key') # pause if clicked2, họ vẫn có thể cần chạy một cái gì đó như #!/usr/bin/python ######################################################### # split a file into a set of portions; join.py puts them # back together; this is a customizable version of the # standard unix split command-line utility; because it # is written in Python, it also works on Windows and can # be easily tweaked; because it exports a function, it # can also be imported and reused in other applications; ######################################################### import sys, os kilobytes = 1024 megabytes = kilobytes * 1000 chunksize = int(1.4 * megabytes) # default: roughly a floppy def split(fromfile, todir, chunksize=chunksize): if not os.path.exists(todir): # caller handles errors os.mkdir(todir) # make dir, read/write parts else: for fname in os.listdir(todir): # delete any existing files os.remove(os.path.join(todir, fname)) partnum = 0 input = open(fromfile, 'rb') # use binary mode on Windows while 1: # eof=empty string from read chunk = input.read(chunksize) # get next part <= chunksize if not chunk: break partnum = partnum+1 filename = os.path.join(todir, ('part%04d' % partnum)) fileobj = open(filename, 'wb') fileobj.write(chunk) fileobj.close() # or simply open( ).write( ) input.close( ) assert partnum <= 9999 # join sort fails if 5 digits return partnum if __name__ == '__main__': if len(sys.argv) == 2 and sys.argv[1] == '-help': print 'Use: split.py [file-to-split target-dir [chunksize]]' else: if len(sys.argv) < 3: interactive = 1 fromfile = raw_input('File to be split? ') # input if clicked todir = raw_input('Directory to store part files? ') else: interactive = 0 fromfile, todir = sys.argv[1:3] # args in cmdline if len(sys.argv) == 4: chunksize = int(sys.argv[3]) absfrom, absto = map(os.path.abspath, [fromfile, todir]) print 'Splitting', absfrom, 'to', absto, 'by', chunksize try: parts = split(fromfile, todir, chunksize) except: print 'Error during split:' print sys.exc_type, sys.exc_value else: print 'Split finished:', parts, 'parts are in', absto if interactive: raw_input('Press Enter key') # pause if clicked3, #!/usr/bin/python ######################################################### # split a file into a set of portions; join.py puts them # back together; this is a customizable version of the # standard unix split command-line utility; because it # is written in Python, it also works on Windows and can # be easily tweaked; because it exports a function, it # can also be imported and reused in other applications; ######################################################### import sys, os kilobytes = 1024 megabytes = kilobytes * 1000 chunksize = int(1.4 * megabytes) # default: roughly a floppy def split(fromfile, todir, chunksize=chunksize): if not os.path.exists(todir): # caller handles errors os.mkdir(todir) # make dir, read/write parts else: for fname in os.listdir(todir): # delete any existing files os.remove(os.path.join(todir, fname)) partnum = 0 input = open(fromfile, 'rb') # use binary mode on Windows while 1: # eof=empty string from read chunk = input.read(chunksize) # get next part <= chunksize if not chunk: break partnum = partnum+1 filename = os.path.join(todir, ('part%04d' % partnum)) fileobj = open(filename, 'wb') fileobj.write(chunk) fileobj.close() # or simply open( ).write( ) input.close( ) assert partnum <= 9999 # join sort fails if 5 digits return partnum if __name__ == '__main__': if len(sys.argv) == 2 and sys.argv[1] == '-help': print 'Use: split.py [file-to-split target-dir [chunksize]]' else: if len(sys.argv) < 3: interactive = 1 fromfile = raw_input('File to be split? ') # input if clicked todir = raw_input('Directory to store part files? ') else: interactive = 0 fromfile, todir = sys.argv[1:3] # args in cmdline if len(sys.argv) == 4: chunksize = int(sys.argv[3]) absfrom, absto = map(os.path.abspath, [fromfile, todir]) print 'Splitting', absfrom, 'to', absto, 'by', chunksize try: parts = split(fromfile, todir, chunksize) except: print 'Error during split:' print sys.exc_type, sys.exc_value else: print 'Split finished:', parts, 'parts are in', absto if interactive: raw_input('Press Enter key') # pause if clicked4 hoặc #!/usr/bin/python ######################################################### # split a file into a set of portions; join.py puts them # back together; this is a customizable version of the # standard unix split command-line utility; because it # is written in Python, it also works on Windows and can # be easily tweaked; because it exports a function, it # can also be imported and reused in other applications; ######################################################### import sys, os kilobytes = 1024 megabytes = kilobytes * 1000 chunksize = int(1.4 * megabytes) # default: roughly a floppy def split(fromfile, todir, chunksize=chunksize): if not os.path.exists(todir): # caller handles errors os.mkdir(todir) # make dir, read/write parts else: for fname in os.listdir(todir): # delete any existing files os.remove(os.path.join(todir, fname)) partnum = 0 input = open(fromfile, 'rb') # use binary mode on Windows while 1: # eof=empty string from read chunk = input.read(chunksize) # get next part <= chunksize if not chunk: break partnum = partnum+1 filename = os.path.join(todir, ('part%04d' % partnum)) fileobj = open(filename, 'wb') fileobj.write(chunk) fileobj.close() # or simply open( ).write( ) input.close( ) assert partnum <= 9999 # join sort fails if 5 digits return partnum if __name__ == '__main__': if len(sys.argv) == 2 and sys.argv[1] == '-help': print 'Use: split.py [file-to-split target-dir [chunksize]]' else: if len(sys.argv) < 3: interactive = 1 fromfile = raw_input('File to be split? ') # input if clicked todir = raw_input('Directory to store part files? ') else: interactive = 0 fromfile, todir = sys.argv[1:3] # args in cmdline if len(sys.argv) == 4: chunksize = int(sys.argv[3]) absfrom, absto = map(os.path.abspath, [fromfile, todir]) print 'Splitting', absfrom, 'to', absto, 'by', chunksize try: parts = split(fromfile, todir, chunksize) except: print 'Error during split:' print sys.exc_type, sys.exc_value else: print 'Split finished:', parts, 'parts are in', absto if interactive: raw_input('Press Enter key') # pause if clicked5 để giải nén tệp lưu trữ, trừ khi nó được vận chuyển là một thực thi; đi vao thực hiện. Dưới đây là sự tham gia của tiến trình trên Windows, kết hợp các tệp phân chia mà chúng tôi đã thực hiện trước đây: C:\temp> Tập lệnh tham gia chỉ cần sử dụng #!/usr/bin/python ######################################################### # split a file into a set of portions; join.py puts them # back together; this is a customizable version of the # standard unix split command-line utility; because it # is written in Python, it also works on Windows and can # be easily tweaked; because it exports a function, it # can also be imported and reused in other applications; ######################################################### import sys, os kilobytes = 1024 megabytes = kilobytes * 1000 chunksize = int(1.4 * megabytes) # default: roughly a floppy def split(fromfile, todir, chunksize=chunksize): if not os.path.exists(todir): # caller handles errors os.mkdir(todir) # make dir, read/write parts else: for fname in os.listdir(todir): # delete any existing files os.remove(os.path.join(todir, fname)) partnum = 0 input = open(fromfile, 'rb') # use binary mode on Windows while 1: # eof=empty string from read chunk = input.read(chunksize) # get next part <= chunksize if not chunk: break partnum = partnum+1 filename = os.path.join(todir, ('part%04d' % partnum)) fileobj = open(filename, 'wb') fileobj.write(chunk) fileobj.close() # or simply open( ).write( ) input.close( ) assert partnum <= 9999 # join sort fails if 5 digits return partnum if __name__ == '__main__': if len(sys.argv) == 2 and sys.argv[1] == '-help': print 'Use: split.py [file-to-split target-dir [chunksize]]' else: if len(sys.argv) < 3: interactive = 1 fromfile = raw_input('File to be split? ') # input if clicked todir = raw_input('Directory to store part files? ') else: interactive = 0 fromfile, todir = sys.argv[1:3] # args in cmdline if len(sys.argv) == 4: chunksize = int(sys.argv[3]) absfrom, absto = map(os.path.abspath, [fromfile, todir]) print 'Splitting', absfrom, 'to', absto, 'by', chunksize try: parts = split(fromfile, todir, chunksize) except: print 'Error during split:' print sys.exc_type, sys.exc_value else: print 'Split finished:', parts, 'parts are in', absto if interactive: raw_input('Press Enter key') # pause if clicked6 để thu thập tất cả các tệp phần trong một thư mục được tạo bởi Split và sắp xếp danh sách tên tệp để đặt các bộ phận lại với nhau theo đúng thứ tự. Chúng tôi lấy lại một bản sao byte chính xác của tệp gốc (được chứng minh bằng lệnh DOS FC ở trên; sử dụng CMP trên UNIX).fc command above; use cmp on Unix). Tất nhiên, một số quá trình này vẫn còn thủ công (tôi đã tìm ra cách viết kịch bản cho bộ phim đi bộ trên lầu, nhưng các tập lệnh 9 và #!/usr/bin/python ######################################################### # split a file into a set of portions; join.py puts them # back together; this is a customizable version of the # standard unix split command-line utility; because it # is written in Python, it also works on Windows and can # be easily tweaked; because it exports a function, it # can also be imported and reused in other applications; ######################################################### import sys, os kilobytes = 1024 megabytes = kilobytes * 1000 chunksize = int(1.4 * megabytes) # default: roughly a floppy def split(fromfile, todir, chunksize=chunksize): if not os.path.exists(todir): # caller handles errors os.mkdir(todir) # make dir, read/write parts else: for fname in os.listdir(todir): # delete any existing files os.remove(os.path.join(todir, fname)) partnum = 0 input = open(fromfile, 'rb') # use binary mode on Windows while 1: # eof=empty string from read chunk = input.read(chunksize) # get next part <= chunksize if not chunk: break partnum = partnum+1 filename = os.path.join(todir, ('part%04d' % partnum)) fileobj = open(filename, 'wb') fileobj.write(chunk) fileobj.close() # or simply open( ).write( ) input.close( ) assert partnum <= 9999 # join sort fails if 5 digits return partnum if __name__ == '__main__': if len(sys.argv) == 2 and sys.argv[1] == '-help': print 'Use: split.py [file-to-split target-dir [chunksize]]' else: if len(sys.argv) < 3: interactive = 1 fromfile = raw_input('File to be split? ') # input if clicked todir = raw_input('Directory to store part files? ') else: interactive = 0 fromfile, todir = sys.argv[1:3] # args in cmdline if len(sys.argv) == 4: chunksize = int(sys.argv[3]) absfrom, absto = map(os.path.abspath, [fromfile, todir]) print 'Splitting', absfrom, 'to', absto, 'by', chunksize try: parts = split(fromfile, todir, chunksize) except: print 'Error during split:' print sys.exc_type, sys.exc_value else: print 'Split finished:', parts, 'parts are in', absto if interactive: raw_input('Press Enter key') # pause if clicked2 làm cho nó nhanh chóng và đơn giản để di chuyển các tệp lớn xung quanh. Bởi vì tập lệnh này cũng là mã python di động, nó chạy trên bất kỳ nền tảng nào chúng tôi quan tâm để chuyển các tệp chia thành. Chẳng hạn, nó điển hình cho trẻ em của tôi tải xuống cả trò chơi Windows và Linux; Kể từ khi tập lệnh này chạy trên một trong hai nền tảng, họ đã được bảo hiểm. Đọc theo khối hoặc tệpTrước khi chúng tôi tiếp tục, có một vài chi tiết đáng để nhấn mạnh trong mã kịch bản tham gia. Trước hết, lưu ý rằng tập lệnh này liên quan đến các tệp ở chế độ nhị phân, nhưng cũng đọc từng tệp một phần trong các khối 1k byte mỗi byte. Trên thực tế, cài đặt #!/usr/bin/python ######################################################### # split a file into a set of portions; join.py puts them # back together; this is a customizable version of the # standard unix split command-line utility; because it # is written in Python, it also works on Windows and can # be easily tweaked; because it exports a function, it # can also be imported and reused in other applications; ######################################################### import sys, os kilobytes = 1024 megabytes = kilobytes * 1000 chunksize = int(1.4 * megabytes) # default: roughly a floppy def split(fromfile, todir, chunksize=chunksize): if not os.path.exists(todir): # caller handles errors os.mkdir(todir) # make dir, read/write parts else: for fname in os.listdir(todir): # delete any existing files os.remove(os.path.join(todir, fname)) partnum = 0 input = open(fromfile, 'rb') # use binary mode on Windows while 1: # eof=empty string from read chunk = input.read(chunksize) # get next part <= chunksize if not chunk: break partnum = partnum+1 filename = os.path.join(todir, ('part%04d' % partnum)) fileobj = open(filename, 'wb') fileobj.write(chunk) fileobj.close() # or simply open( ).write( ) input.close( ) assert partnum <= 9999 # join sort fails if 5 digits return partnum if __name__ == '__main__': if len(sys.argv) == 2 and sys.argv[1] == '-help': print 'Use: split.py [file-to-split target-dir [chunksize]]' else: if len(sys.argv) < 3: interactive = 1 fromfile = raw_input('File to be split? ') # input if clicked todir = raw_input('Directory to store part files? ') else: interactive = 0 fromfile, todir = sys.argv[1:3] # args in cmdline if len(sys.argv) == 4: chunksize = int(sys.argv[3]) absfrom, absto = map(os.path.abspath, [fromfile, todir]) print 'Splitting', absfrom, 'to', absto, 'by', chunksize try: parts = split(fromfile, todir, chunksize) except: print 'Error during split:' print sys.exc_type, sys.exc_value else: print 'Split finished:', parts, 'parts are in', absto if interactive: raw_input('Press Enter key') # pause if clicked9 ở đây (kích thước của mỗi khối được đọc từ tệp phần đầu vào) không liên quan đến C:\temp>0 trong C:\temp>1 (tổng kích thước của mỗi tệp phần đầu ra). Như chúng ta đã học trong Chương 2, tập lệnh này thay vào đó có thể đọc từng tệp phần cùng một lúc: 0Nhược điểm của sơ đồ này là nó thực sự tải tất cả một tệp vào bộ nhớ cùng một lúc. Ví dụ: đọc tệp phần 1,4m vào bộ nhớ cùng một lúc với phương thức đối tượng tệp C:\temp>2 tạo ra chuỗi 1,4m trong bộ nhớ để giữ các byte tệp tệp. Vì 9 cho phép người dùng chỉ định các kích thước chunk thậm chí lớn hơn, nên các kế hoạch tập lệnh #!/usr/bin/python ######################################################### # split a file into a set of portions; join.py puts them # back together; this is a customizable version of the # standard unix split command-line utility; because it # is written in Python, it also works on Windows and can # be easily tweaked; because it exports a function, it # can also be imported and reused in other applications; ######################################################### import sys, os kilobytes = 1024 megabytes = kilobytes * 1000 chunksize = int(1.4 * megabytes) # default: roughly a floppy def split(fromfile, todir, chunksize=chunksize): if not os.path.exists(todir): # caller handles errors os.mkdir(todir) # make dir, read/write parts else: for fname in os.listdir(todir): # delete any existing files os.remove(os.path.join(todir, fname)) partnum = 0 input = open(fromfile, 'rb') # use binary mode on Windows while 1: # eof=empty string from read chunk = input.read(chunksize) # get next part <= chunksize if not chunk: break partnum = partnum+1 filename = os.path.join(todir, ('part%04d' % partnum)) fileobj = open(filename, 'wb') fileobj.write(chunk) fileobj.close() # or simply open( ).write( ) input.close( ) assert partnum <= 9999 # join sort fails if 5 digits return partnum if __name__ == '__main__': if len(sys.argv) == 2 and sys.argv[1] == '-help': print 'Use: split.py [file-to-split target-dir [chunksize]]' else: if len(sys.argv) < 3: interactive = 1 fromfile = raw_input('File to be split? ') # input if clicked todir = raw_input('Directory to store part files? ') else: interactive = 0 fromfile, todir = sys.argv[1:3] # args in cmdline if len(sys.argv) == 4: chunksize = int(sys.argv[3]) absfrom, absto = map(os.path.abspath, [fromfile, todir]) print 'Splitting', absfrom, 'to', absto, 'by', chunksize try: parts = split(fromfile, todir, chunksize) except: print 'Error during split:' print sys.exc_type, sys.exc_value else: print 'Split finished:', parts, 'parts are in', absto if interactive: raw_input('Press Enter key') # pause if clicked2 cho các kế hoạch tồi tệ nhất và đọc theo các khối có kích thước giới hạn. Để hoàn toàn mạnh mẽ, tập lệnh 9 cũng có thể đọc dữ liệu đầu vào của mình bằng các khối nhỏ hơn, nhưng điều này đã trở thành một mối quan tâm trong thực tế.Sắp xếp tên tệpNếu bạn nghiên cứu mật mã tập lệnh này một cách chặt chẽ, bạn cũng có thể nhận thấy rằng sơ đồ tham gia mà nó sử dụng phụ thuộc hoàn toàn vào thứ tự sắp xếp tên tệp trong thư mục bộ phận. Bởi vì nó chỉ đơn giản gọi phương thức danh sách C:\temp>6 trên danh sách tên tệp được trả về bởi #!/usr/bin/python ######################################################### # split a file into a set of portions; join.py puts them # back together; this is a customizable version of the # standard unix split command-line utility; because it # is written in Python, it also works on Windows and can # be easily tweaked; because it exports a function, it # can also be imported and reused in other applications; ######################################################### import sys, os kilobytes = 1024 megabytes = kilobytes * 1000 chunksize = int(1.4 * megabytes) # default: roughly a floppy def split(fromfile, todir, chunksize=chunksize): if not os.path.exists(todir): # caller handles errors os.mkdir(todir) # make dir, read/write parts else: for fname in os.listdir(todir): # delete any existing files os.remove(os.path.join(todir, fname)) partnum = 0 input = open(fromfile, 'rb') # use binary mode on Windows while 1: # eof=empty string from read chunk = input.read(chunksize) # get next part <= chunksize if not chunk: break partnum = partnum+1 filename = os.path.join(todir, ('part%04d' % partnum)) fileobj = open(filename, 'wb') fileobj.write(chunk) fileobj.close() # or simply open( ).write( ) input.close( ) assert partnum <= 9999 # join sort fails if 5 digits return partnum if __name__ == '__main__': if len(sys.argv) == 2 and sys.argv[1] == '-help': print 'Use: split.py [file-to-split target-dir [chunksize]]' else: if len(sys.argv) < 3: interactive = 1 fromfile = raw_input('File to be split? ') # input if clicked todir = raw_input('Directory to store part files? ') else: interactive = 0 fromfile, todir = sys.argv[1:3] # args in cmdline if len(sys.argv) == 4: chunksize = int(sys.argv[3]) absfrom, absto = map(os.path.abspath, [fromfile, todir]) print 'Splitting', absfrom, 'to', absto, 'by', chunksize try: parts = split(fromfile, todir, chunksize) except: print 'Error during split:' print sys.exc_type, sys.exc_value else: print 'Split finished:', parts, 'parts are in', absto if interactive: raw_input('Press Enter key') # pause if clicked6, nên nó hoàn toàn yêu cầu các tên tệp có cùng độ dài và định dạng khi được tạo bởi Split. Bộ chia sử dụng ký hiệu không có padding trong biểu thức định dạng chuỗi ( C:\temp>8) để đảm bảo rằng tên tệp đều có cùng số chữ số ở cuối (bốn), giống như danh sách này: 1Khi được sắp xếp, các ký tự 0 hàng đầu trong các số nhỏ đảm bảo rằng các tệp một phần được đặt hàng để tham gia chính xác. Nếu không có số 0 hàng đầu, #!/usr/bin/python ######################################################### # split a file into a set of portions; join.py puts them # back together; this is a customizable version of the # standard unix split command-line utility; because it # is written in Python, it also works on Windows and can # be easily tweaked; because it exports a function, it # can also be imported and reused in other applications; ######################################################### import sys, os kilobytes = 1024 megabytes = kilobytes * 1000 chunksize = int(1.4 * megabytes) # default: roughly a floppy def split(fromfile, todir, chunksize=chunksize): if not os.path.exists(todir): # caller handles errors os.mkdir(todir) # make dir, read/write parts else: for fname in os.listdir(todir): # delete any existing files os.remove(os.path.join(todir, fname)) partnum = 0 input = open(fromfile, 'rb') # use binary mode on Windows while 1: # eof=empty string from read chunk = input.read(chunksize) # get next part <= chunksize if not chunk: break partnum = partnum+1 filename = os.path.join(todir, ('part%04d' % partnum)) fileobj = open(filename, 'wb') fileobj.write(chunk) fileobj.close() # or simply open( ).write( ) input.close( ) assert partnum <= 9999 # join sort fails if 5 digits return partnum if __name__ == '__main__': if len(sys.argv) == 2 and sys.argv[1] == '-help': print 'Use: split.py [file-to-split target-dir [chunksize]]' else: if len(sys.argv) < 3: interactive = 1 fromfile = raw_input('File to be split? ') # input if clicked todir = raw_input('Directory to store part files? ') else: interactive = 0 fromfile, todir = sys.argv[1:3] # args in cmdline if len(sys.argv) == 4: chunksize = int(sys.argv[3]) absfrom, absto = map(os.path.abspath, [fromfile, todir]) print 'Splitting', absfrom, 'to', absto, 'by', chunksize try: parts = split(fromfile, todir, chunksize) except: print 'Error during split:' print sys.exc_type, sys.exc_value else: print 'Split finished:', parts, 'parts are in', absto if interactive: raw_input('Press Enter key') # pause if clicked2 sẽ thất bại bất cứ khi nào có hơn chín tệp, bởi vì chữ số đầu tiên sẽ chiếm ưu thế: 2Bởi vì phương thức danh sách C:\temp>6 chấp nhận hàm so sánh làm đối số, về mặt nguyên tắc, chúng ta có thể loại bỏ các chữ số trong tên tệp và sắp xếp số lượng: 3Nhưng điều đó vẫn ngụ ý rằng tất cả các tên tệp phải bắt đầu với cùng một chuỗi con độ dài, vì vậy điều này không loại bỏ phụ thuộc đặt tên tệp giữa các tập lệnh 9 và #!/usr/bin/python ######################################################### # split a file into a set of portions; join.py puts them # back together; this is a customizable version of the # standard unix split command-line utility; because it # is written in Python, it also works on Windows and can # be easily tweaked; because it exports a function, it # can also be imported and reused in other applications; ######################################################### import sys, os kilobytes = 1024 megabytes = kilobytes * 1000 chunksize = int(1.4 * megabytes) # default: roughly a floppy def split(fromfile, todir, chunksize=chunksize): if not os.path.exists(todir): # caller handles errors os.mkdir(todir) # make dir, read/write parts else: for fname in os.listdir(todir): # delete any existing files os.remove(os.path.join(todir, fname)) partnum = 0 input = open(fromfile, 'rb') # use binary mode on Windows while 1: # eof=empty string from read chunk = input.read(chunksize) # get next part <= chunksize if not chunk: break partnum = partnum+1 filename = os.path.join(todir, ('part%04d' % partnum)) fileobj = open(filename, 'wb') fileobj.write(chunk) fileobj.close() # or simply open( ).write( ) input.close( ) assert partnum <= 9999 # join sort fails if 5 digits return partnum if __name__ == '__main__': if len(sys.argv) == 2 and sys.argv[1] == '-help': print 'Use: split.py [file-to-split target-dir [chunksize]]' else: if len(sys.argv) < 3: interactive = 1 fromfile = raw_input('File to be split? ') # input if clicked todir = raw_input('Directory to store part files? ') else: interactive = 0 fromfile, todir = sys.argv[1:3] # args in cmdline if len(sys.argv) == 4: chunksize = int(sys.argv[3]) absfrom, absto = map(os.path.abspath, [fromfile, todir]) print 'Splitting', absfrom, 'to', absto, 'by', chunksize try: parts = split(fromfile, todir, chunksize) except: print 'Error during split:' print sys.exc_type, sys.exc_value else: print 'Split finished:', parts, 'parts are in', absto if interactive: raw_input('Press Enter key') # pause if clicked2. Tuy nhiên, bởi vì các tập lệnh này được thiết kế là hai bước của cùng một quy trình, một số phụ thuộc giữa chúng có vẻ hợp lý. Biến thể sử dụngHãy cùng chạy thêm một vài thí nghiệm với các tiện ích hệ thống Python này để chứng minh các chế độ sử dụng khác. Khi chạy mà không có các đối số dòng lệnh đầy đủ, cả 9 và #!/usr/bin/python ######################################################### # split a file into a set of portions; join.py puts them # back together; this is a customizable version of the # standard unix split command-line utility; because it # is written in Python, it also works on Windows and can # be easily tweaked; because it exports a function, it # can also be imported and reused in other applications; ######################################################### import sys, os kilobytes = 1024 megabytes = kilobytes * 1000 chunksize = int(1.4 * megabytes) # default: roughly a floppy def split(fromfile, todir, chunksize=chunksize): if not os.path.exists(todir): # caller handles errors os.mkdir(todir) # make dir, read/write parts else: for fname in os.listdir(todir): # delete any existing files os.remove(os.path.join(todir, fname)) partnum = 0 input = open(fromfile, 'rb') # use binary mode on Windows while 1: # eof=empty string from read chunk = input.read(chunksize) # get next part <= chunksize if not chunk: break partnum = partnum+1 filename = os.path.join(todir, ('part%04d' % partnum)) fileobj = open(filename, 'wb') fileobj.write(chunk) fileobj.close() # or simply open( ).write( ) input.close( ) assert partnum <= 9999 # join sort fails if 5 digits return partnum if __name__ == '__main__': if len(sys.argv) == 2 and sys.argv[1] == '-help': print 'Use: split.py [file-to-split target-dir [chunksize]]' else: if len(sys.argv) < 3: interactive = 1 fromfile = raw_input('File to be split? ') # input if clicked todir = raw_input('Directory to store part files? ') else: interactive = 0 fromfile, todir = sys.argv[1:3] # args in cmdline if len(sys.argv) == 4: chunksize = int(sys.argv[3]) absfrom, absto = map(os.path.abspath, [fromfile, todir]) print 'Splitting', absfrom, 'to', absto, 'by', chunksize try: parts = split(fromfile, todir, chunksize) except: print 'Error during split:' print sys.exc_type, sys.exc_value else: print 'Split finished:', parts, 'parts are in', absto if interactive: raw_input('Press Enter key') # pause if clicked2 đều đủ thông minh để nhập các tham số của chúng một cách tương tác. Ở đây, họ đang cắt và dán lại tệp tự cài đặt Python trên Windows, với các tham số được gõ trong cửa sổ Bảng điều khiển DOS:interactively. Here they are chopping and gluing the Python self-installer file on Windows again, with parameters typed in the DOS console window: 4Khi các tệp chương trình này được nhấp đúp vào GUI tệp Explorer, chúng hoạt động theo cùng một cách (thường không có đối số dòng lệnh khi được khởi chạy theo cách này). Trong chế độ này, đường dẫn tuyệt đối hiển thị giúp làm rõ nơi các tệp thực sự tại. Hãy nhớ rằng, thư mục làm việc hiện tại là thư mục nhà tập lệnh khi được nhấp như thế này, vì vậy tên fileobj = open(partname, 'wb') fileobj.write(chunk) fileobj.close( )5 thực sự ánh xạ vào thư mục mã nguồn; Nhập một đường dẫn đầy đủ để làm cho các tệp phân chia hiển thị ở một nơi khác: 5Tuy nhiên, bởi vì các tập lệnh này gói logic cốt lõi của chúng trong các chức năng, nên nó rất dễ sử dụng lại mã của chúng bằng cách nhập và gọi từ một thành phần Python khác: 6Một từ về hiệu suất: Tất cả các thử nghiệm 9 và #!/usr/bin/python ######################################################### # split a file into a set of portions; join.py puts them # back together; this is a customizable version of the # standard unix split command-line utility; because it # is written in Python, it also works on Windows and can # be easily tweaked; because it exports a function, it # can also be imported and reused in other applications; ######################################################### import sys, os kilobytes = 1024 megabytes = kilobytes * 1000 chunksize = int(1.4 * megabytes) # default: roughly a floppy def split(fromfile, todir, chunksize=chunksize): if not os.path.exists(todir): # caller handles errors os.mkdir(todir) # make dir, read/write parts else: for fname in os.listdir(todir): # delete any existing files os.remove(os.path.join(todir, fname)) partnum = 0 input = open(fromfile, 'rb') # use binary mode on Windows while 1: # eof=empty string from read chunk = input.read(chunksize) # get next part <= chunksize if not chunk: break partnum = partnum+1 filename = os.path.join(todir, ('part%04d' % partnum)) fileobj = open(filename, 'wb') fileobj.write(chunk) fileobj.close() # or simply open( ).write( ) input.close( ) assert partnum <= 9999 # join sort fails if 5 digits return partnum if __name__ == '__main__': if len(sys.argv) == 2 and sys.argv[1] == '-help': print 'Use: split.py [file-to-split target-dir [chunksize]]' else: if len(sys.argv) < 3: interactive = 1 fromfile = raw_input('File to be split? ') # input if clicked todir = raw_input('Directory to store part files? ') else: interactive = 0 fromfile, todir = sys.argv[1:3] # args in cmdline if len(sys.argv) == 4: chunksize = int(sys.argv[3]) absfrom, absto = map(os.path.abspath, [fromfile, todir]) print 'Splitting', absfrom, 'to', absto, 'by', chunksize try: parts = split(fromfile, todir, chunksize) except: print 'Error during split:' print sys.exc_type, sys.exc_value else: print 'Split finished:', parts, 'parts are in', absto if interactive: raw_input('Press Enter key') # pause if clicked2 hiển thị cho đến nay xử lý một tệp 5m, nhưng mất nhiều nhất một giây thời gian đồng hồ treo tường thực để hoàn thành trên các máy tính xách tay của tôi- sẽ tăng tốc 98 300 và 650 MHz- rất nhanh cho Chỉ cần sử dụng bất kỳ tôi có thể tưởng tượng. . Dưới đây là bộ chia cắt tệp thành các bộ phận 500.000 và 50.000 byte: 7Chia có thể mất nhiều thời gian hơn để hoàn thành, nhưng chỉ khi kích thước của tệp phần được đặt đủ nhỏ để tạo hàng ngàn tệp - chia thành 1006 phần hoạt động, nhưng chạy chậm hơn (trên máy tính của tôi chia và tham gia mất khoảng năm và hai giây, tương ứng, tùy thuộc vào những chương trình khác được mở): 8Cuối cùng, bộ chia cũng đủ thông minh để tạo thư mục đầu ra nếu nó chưa tồn tại hoặc xóa bất kỳ tệp cũ nào ở đó nếu nó tồn tại. Bởi vì người tham gia kết hợp bất kỳ tệp nào tồn tại trong thư mục đầu ra, đây là một liên lạc công thái học đẹp - nếu thư mục đầu ra không được xóa trước mỗi lần chia, sẽ quá dễ để quên rằng các tệp chạy trước đó vẫn còn đó. Cho rằng những đứa trẻ của tôi đang điều hành các kịch bản này, chúng cần phải tha thứ nhất có thể; Cơ sở người dùng của bạn có thể khác nhau, nhưng có lẽ không nhiều. 9Nhận lập trình Python, phiên bản thứ hai ngay bây giờ với nền tảng học tập O hèReilly.learning platform. Các thành viên của O hèReilly trải nghiệm đào tạo trực tuyến trực tiếp, cộng với sách, video và nội dung kỹ thuật số từ gần 200 nhà xuất bản.nearly 200 publishers. |