I wrote these as helpers when creating a "live" version of pyzo.leo
<https://github.com/edreamleo/pyzo/blob/master/pyzo.leo>. See notes in #1097
importing to @clean <https://github.com/leo-editor/leo-editor/issues/1097>.
*g.get_files_in_directory* returns a sorted list of all files in a
directory and subdirectories. It's a helper for the second script, shown
below.
def get_files_in_directory(directory, kinds=None, recursive=True):
'''
Return a list of all files of the given file extensions in the
directory.
Default kinds: ['*.py'].
'''
files, sep = [], os.path.sep
if not g.os.path.exists(directory):
g.es_print('does not exist', directory)
return files
try:
if kinds:
kinds = [z if z.startswith('*') else '*'+z for z in kinds]
else:
kinds = ['*.py']
if recursive:
# Works for all versions of Python.
import fnmatch
for root, dirnames, filenames in os.walk(directory):
for kind in kinds:
for filename in fnmatch.filter(filenames, kind):
files.append(os.path.join(root, filename))
else:
for kind in kinds:
files.extend(glob.glob(directory + sep + kind))
return list(set(sorted(files)))
except Exception:
g.es_exception()
return []
Here is the script that cleans all blank lines in a directory:
directory = r'C:\apps\pyzo\source\pyzo'
def clean_dir(directory):
for path in g.get_files_in_directory(directory, kinds=['.py']):
clean_file(path)
def clean_file(path):
with open(path, 'r') as f:
file_s = f.read()
lines = []
for line in g.splitLines(file_s):
if line.rstrip():
lines.append(line.rstrip())
if line.endswith('\n'):
lines.append('\n')
new_s = ''.join(lines)
if file_s != new_s:
with open(path, 'w') as f:
f.write(new_s)
print('wrote: %s' % path)
clean_dir(directory)
Edward
--
You received this message because you are subscribed to the Google Groups
"leo-editor" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To post to this group, send email to [email protected].
Visit this group at https://groups.google.com/group/leo-editor.
For more options, visit https://groups.google.com/d/optout.