Skip to content

Instantly share code, notes, and snippets.

@nilox94
Created June 13, 2018 16:23
Show Gist options
  • Save nilox94/7d482f0241481f361f1a113c532946e4 to your computer and use it in GitHub Desktop.
Save nilox94/7d482f0241481f361f1a113c532946e4 to your computer and use it in GitHub Desktop.
Converts CRLF to LF in a file or recursively in all files of a directory
#!/usr/bin/env python
import argparse, os, sys
(
NO_ERR,
READ_ERR,
WRITE_ERR,
BACKUP_ERR,
) = range(4)
ERR_HDR = {
READ_ERR: 'ERROR reading file %s',
WRITE_ERR: 'ERROR writing file %s',
BACKUP_ERR: 'ERROR backing up file %s',
}
ERR_EXIT = -1
def bak_name(name):
bak = name +'.bak'
i = 1
while os.path.isfile(bak):
bak ='%s.bak.%d' % (name, i)
i += 1
return bak
def crlf2lf(file_name, backup=False):
try:
with open(file_name, 'r') as f:
text = f.read()
except e:
return READ_ERR, e
try:
if backup:
os.rename(file_name, file_name+'.bak')
except e:
return BACKUP_ERR, e
try:
with open(file_name, 'w') as f:
text = text.replace('\r\n', '\n')
f.write(text)
except e:
return WRITE_ERR, e
return NO_ERR, None
def process_file(file_name, backup):
err_type, err_msg = crlf2lf(file_name, backup)
if err_type != NO_ERR:
print('%s\n%s' % (ERR_HDR[err_type] % file_name, err_msg))
return ERR_EXIT
return 0
def process_dir(dir_name, backup):
exit_code = 0
for base, _, file_names in os.walk(dirname):
for file_name in file_names:
exit_code |= process_file(os.path.join(base, file_name), backup)
return exit_code
def main():
parser = argparse.ArgumentParser(
description='converts CRLF to LF in a file or recursively in all files of a directory')
parser.add_argument(
'path', default='.', type=str,
help='source file or directory')
parser.add_argument(
'--backup', default=False, type=bool,
help='backup original file')
args = parser.parse_args()
if os.path.isfile(args.path):
exit(process_file(args.path, args.backup))
if os.path.isdir(args.path):
exit(process_dir(args.path, args.backup))
print('`%s` is not an existing file or directory' % path)
exit(ERR_EXIT)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment