#!/usr/bin/python3 # A script to parse all text files in a directory and remove blank lines # Copyright (C) 2022 Louis Lacoste # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with this program. If not, see . import argparse from pathlib import Path parser = argparse.ArgumentParser() parser.add_argument("directory", metavar="DIRECTORY", help="The directory in where are stored the text files") parser.add_argument("-v", "--verbose", action="store_true", help="Enable verbose mode") args = parser.parse_args() path = Path(args.directory) textFiles = list(path.glob("*.txt")) if args.verbose: print("Text files:") for textFile in textFiles: print(f"- {textFile.name}") for textFile in textFiles: if textFile.exists() and not textFile.is_dir(): fileContentString = "" fileContentList = [] if args.verbose: print(f"\nRemoving empty lines for {textFile.name}") with textFile.open(encoding="utf8") as currentTextFile: fileContentString = currentTextFile.read() fileContentList = [ line for line in fileContentString.split('\n') if line.strip()] with textFile.with_name(textFile.name[:-4] + "-noemptylines" + textFile.name[-4:]).open(mode="w", encoding="utf8") as currentTextFile: for line in fileContentList: currentTextFile.write(f"{line}\n")