License New BSD license
Lines 121
Keywords
directory tree (2) file management (6) tabs to spaces (1)
Permissions
Group Owner: iCapsid
Viewable by Everyone
Editable by All Siafoo Users

Convert Tabs to Spaces in Multiple Files Atom Feed 1

In Brief Traverses a directory tree (or a single file) and converts tabs to spaces. Color-coded output makes it easy to determine changed and unchanged files and read/write errors.... more
# 's
  1#!/usr/bin/python
2
3# By David Isaacson
4# Copyright 2008 Siafoo.net
5# New BSD License
6
7'''
8Takes a file or directory and replaces tabs with spaces.
9Usage:
10 python tabs_to_spaces.py [-v] path
11'''
12
13import re
14import os
15import sys
16
17from getopt import gnu_getopt as getopt, GetoptError
18
19class ReadError(IOError): pass
20class WriteError(IOError): pass
21
22red_start = '\033[1;31m'
23green_start = '\033[1;32m'
24color_end = '\033[1;m'
25
26def main(argv):
27 verbose = False
28
29 try:
30 pairs, args = getopt(argv, 'v')
31 if len(args) != 1:
32 raise GetoptError, 'Need more args'
33
34 except GetoptError:
35 print __doc__
36 return
37
38 for option, value in pairs:
39 if option == '-v':
40 verbose = True
41
42 files_changed = 0
43 read_errors = 0
44 write_errors = 0
45
46 files = walk(args[0])
47
48 # Do the deed
49 for file in files:
50 try:
51 if transform(file):
52 files_changed += 1
53 if verbose:
54 print '%s%s (modified)%s' % (green_start, file, color_end)
55 elif verbose:
56 print '%s (unmodified)' % file
57
58 except ReadError:
59 read_errors += 1
60 print '%sError: File %s could not be read.%s' % (red_start, file, color_end)
61
62 except WriteError:
63 write_errors += 1
64 print '%sError: File %s could not be written to.%s' %(red_start, file, color_end)
65
66 # Result Output
67 print
68 print 'Results:'
69 print green_start + ' %i files transformed.' % files_changed + color_end
70 print ' %i files unmodified.' % (len(files) - files_changed - read_errors - write_errors)
71
72 if read_errors:
73 print red_start + ' %i files could not be read.' % read_errors + color_end
74 if write_errors:
75 print red_start + ' %i files could not be written to.' % write_errors + color_end
76
77
78def transform(file):
79 '''Opens file and replaces tabs with spaces, then writes new file to disk.'''
80
81 try:
82 handle = open(file, 'rb')
83 text = handle.read()
84 handle.close()
85
86 except IOError:
87 raise ReadError
88
89 # Bail if nothing to transform
90 if not re.search(r'\t', text):
91 return False
92
93 text = re.sub(r'\t', ' ', text)
94
95 try:
96 handle = open(file, 'wb')
97 handle.write(text)
98 handle.close()
99
100 except IOError:
101 raise WriteError
102
103 return True
104
105
106def walk(path, relative = False, dotdirs = False):
107 '''
108 Given a 'path', traverses the directory tree and returns every file (every non-directory) found.
109 If 'relative' is True, the path is not converted into an absolute path.
110 If 'dotdirs' is True, directories that start with a '.' are included.
111 Otherwise they and their contents are excluded.
112
113 This function is placed in the Public Domain.
114 '''
115
116 if not relative:
117 path = os.path.abspath(path)
118
119
120 if os.path.isfile(path):
121 return [path]
122
123 elif os.path.isdir(path):
124 files = []
125 for dirpath, dirnames, filenames in os.walk(path):
126 if not dotdirs:
127 # Modify list in place -- there is probably a better way to do this
128 for dir in dirnames:
129 if dir.startswith('.'):
130 dirnames.pop(dirnames.index(dir))
131
132 files.extend(os.path.join(dirpath, file) for file in filenames)
133 return files
134
135 else:
136 raise ValueError, 'Not sure how to handle that sort of file.'
137
138
139if __name__ == "__main__":
140 main(sys.argv[1:])

Traverses a directory tree (or a single file) and converts tabs to spaces. Color-coded output makes it easy to determine changed and unchanged files and read/write errors.

Usage:
tabs_to_spaces.py [-v] path/to/convert

The -v will print out each file, green if it was changed and black otherwise. Read/write errors will always print.

Incorporates Get Every File in a Directory Tree