Specific examples of Python merge files

Source: Internet
Author: User
Two types of usage are supported:
(1) Merging all files under a folder (ignoring non-file items such as folders)
(2) Display of merged multiple files.
Copy CodeThe code is as follows:


Import Sys
Import OS
'''
Usage (1): Merge_files pathname
Pathname is directory and the merge files in pathname directory
Usage (2): Merge_files file1 file2 [file3[...]
'''
File_slim = (256* (1024*1024)) #256M match 2**n
def merge_files (fileslist,mfname):
Global File_slim
P_FP = open (Mfname, "WBA")
For file in Fileslist:
With open (file, "RB") as C_FP:
Fsize = Os.stat (file). st_size
Count = Fsize&file_slim
While count>0:
P_fp.write (C_fp.read (File_slim))
Fsize-= File_slim
Count-= 1
P_fp.write (C_fp.read ())
P_fp.close
def main ():
ARGC = Len (sys.argv)-1
Fileslist = []
if argc = = 2:
Dir_name = Os.path.realpath (sys.argv[1])
ASSERT (Os.path.isdir (dir_name))
File_dir = Os.listdir (dir_name)
Fileslist = [Os.path.join (dir_name,file) for file in File_dir if Os.path.isfile (Os.path.join (dir_name,file))]
Print (fileslist)
Elif argc >=3:
Fileslist = [Os.path.realpath (Sys.argv[index]) for index in range (1,ARGC) if Os.path.isfile (Os.path.realpath (sys.argv[ Index])]
Merge_files (FILESLIST,SYS.ARGV[ARGC])
if __name__ = = ' __main__ ':
Main ()
  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.