Using python to write text files with DOS line endings on linux

后端 未结 5 1763
野性不改
野性不改 2021-02-18 17:40

I want to write text files with DOS/Windows line endings \'\\r\\n\' using python running on Linux. It seems to me that there must be a better way than manually putting a \'\\r\\

5条回答
  •  清歌不尽
    2021-02-18 18:21

    Here's a python script I wrote. It recurses from a given directory, replacing all \n line endings with \r\n endings. Use it like this:

    unix2windows /path/to/some/directory
    

    It ignores files in folders beginning with a '.'. It also ignores files that it thinks are binary files, using the approach given by J.F. Sebastian in this answer. You can filter further by using the optional regex positional argument:

    unix2windows /path/to/some/directory .py$
    

    Here's the script in full. For the avoidance of doubt, my parts are licensed under the MIT licence.

    #!/usr/bin/python
    import sys
    import os
    import re
    from os.path import join
    
    textchars = bytearray({7,8,9,10,12,13,27} | set(range(0x20, 0x100)) - {0x7f})
    def is_binary_string(bytes):
        return bool(bytes.translate(None, textchars))
    
    def is_binary_file(path):    
        with open(path, 'rb') as f:
            return is_binary_string(f.read(1024))
    
    def convert_file(path):
        if not is_binary_file(path):
            with open(path, 'r') as f:
                text = f.read()
            print path
        with open(path, 'wb') as f:
            f.write(text.replace('\r', '').replace('\n', '\r\n'))
    
    def convert_dir(root_path, pattern):
        for root, dirs, files in os.walk(root_path):
            for filename in files:
                if pattern.search(filename):
                    path = join(root, filename)
                    convert_file(path)
    
            # Don't walk hidden dirs
            for dir in list(dirs):
                if dir[0] == '.':
                    dirs.remove(dir)
    
    args = sys.argv
    if len(args) <= 1 or len(args) > 3:
        print "This tool recursively converts files from Unix line endings to"
        print "Windows line endings"
        print ""
        print "USAGE: unix2windows.py PATH [REGEX]"
        print "Path:             The directory to begin recursively searching from"
        print "Regex (optional): Only files matching this regex will be modified"
        print ""    
    else:
        root_path = sys.argv[1]
        if len(args) == 3:
            pattern = sys.argv[2]
        else:
            pattern = r"."
        convert_dir(root_path, re.compile(pattern))
    

提交回复
热议问题