Chris@87: """ Functions for converting from DOS to UNIX line endings Chris@87: Chris@87: """ Chris@87: from __future__ import division, absolute_import, print_function Chris@87: Chris@87: import sys, re, os Chris@87: Chris@87: def dos2unix(file): Chris@87: "Replace CRLF with LF in argument files. Print names of changed files." Chris@87: if os.path.isdir(file): Chris@87: print(file, "Directory!") Chris@87: return Chris@87: Chris@87: data = open(file, "rb").read() Chris@87: if '\0' in data: Chris@87: print(file, "Binary!") Chris@87: return Chris@87: Chris@87: newdata = re.sub("\r\n", "\n", data) Chris@87: if newdata != data: Chris@87: print('dos2unix:', file) Chris@87: f = open(file, "wb") Chris@87: f.write(newdata) Chris@87: f.close() Chris@87: return file Chris@87: else: Chris@87: print(file, 'ok') Chris@87: Chris@87: def dos2unix_one_dir(modified_files, dir_name, file_names): Chris@87: for file in file_names: Chris@87: full_path = os.path.join(dir_name, file) Chris@87: file = dos2unix(full_path) Chris@87: if file is not None: Chris@87: modified_files.append(file) Chris@87: Chris@87: def dos2unix_dir(dir_name): Chris@87: modified_files = [] Chris@87: os.path.walk(dir_name, dos2unix_one_dir, modified_files) Chris@87: return modified_files Chris@87: #---------------------------------- Chris@87: Chris@87: def unix2dos(file): Chris@87: "Replace LF with CRLF in argument files. Print names of changed files." Chris@87: if os.path.isdir(file): Chris@87: print(file, "Directory!") Chris@87: return Chris@87: Chris@87: data = open(file, "rb").read() Chris@87: if '\0' in data: Chris@87: print(file, "Binary!") Chris@87: return Chris@87: newdata = re.sub("\r\n", "\n", data) Chris@87: newdata = re.sub("\n", "\r\n", newdata) Chris@87: if newdata != data: Chris@87: print('unix2dos:', file) Chris@87: f = open(file, "wb") Chris@87: f.write(newdata) Chris@87: f.close() Chris@87: return file Chris@87: else: Chris@87: print(file, 'ok') Chris@87: Chris@87: def unix2dos_one_dir(modified_files, dir_name, file_names): Chris@87: for file in file_names: Chris@87: full_path = os.path.join(dir_name, file) Chris@87: unix2dos(full_path) Chris@87: if file is not None: Chris@87: modified_files.append(file) Chris@87: Chris@87: def unix2dos_dir(dir_name): Chris@87: modified_files = [] Chris@87: os.path.walk(dir_name, unix2dos_one_dir, modified_files) Chris@87: return modified_files Chris@87: Chris@87: if __name__ == "__main__": Chris@87: dos2unix_dir(sys.argv[1])