-
Notifications
You must be signed in to change notification settings - Fork 2
/
whitespace.py
91 lines (65 loc) · 1.93 KB
/
whitespace.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
"""Module to handle whitespace in text files."""
from __future__ import division, print_function
# STDLIB
import os
import re
import sys
__author__ = 'Pey Lian Lim'
__organization__ = 'Space Telescope Science Institute'
def find_trailing_ws(infile, verbose=True):
"""Find occurences of trailing whitespace.
Parameters
----------
infile: str
Input text file.
verbose: bool
Print extra info to screen.
Returns
-------
found: bool
True if any line has trailing whitespace.
"""
assert os.path.exists(infile), 'Input not found.'
n_match = 0
with open(infile, 'r') as fin:
for i, line in enumerate(fin, 1):
s = line.rstrip(os.linesep)
if len(s) > 0 and re.search('\s', s[-1]):
n_match += 1
if verbose:
print('{}. Line {}: "{}\\n"'.format(n_match, i, s))
else:
break # Stop at first occurence if not verbose
if verbose:
print('\nTOTAL:', n_match, 'lines\n\n')
if n_match == 0:
return False
else:
return True
def del_trailing_ws(infile, outfile):
"""Delete trailing whitespace.
Parameters
----------
infile: str
Input text file.
outfile: str
Output text file.
"""
assert infile != outfile, 'Input and output are the same.'
assert os.path.exists(infile), 'Input not found.'
if os.path.exists(outfile):
do_overwrite = True
else:
do_overwrite = False
fout = open(outfile, 'w')
with open(infile, 'r') as fin:
for line in fin:
fout.write(line.rstrip() + os.linesep)
fout.close()
if do_overwrite:
print(outfile, 'overwritten.')
else:
print(outfile, 'written.')
if __name__ == '__main__':
assert len(sys.argv) == 3, 'Usage: python whitespace.py infile outfile'
del_trailing_ws(sys.argv[1], sys.argv[2])