useful-scripts/text-scripts/blank-lines-remove.py

42 lines
No EOL
1.6 KiB
Python

#!/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 <https://www.gnu.org/licenses/>.
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")
args = parser.parse_args()
path = Path(args.directory)
textFiles = list(path.glob("*.txt"))
print(textFiles)
for textFile in textFiles:
if textFile.exists() and not textFile.is_dir():
fileContentString = ""
fileContentList = []
with textFile.open(encoding="utf8") as currentTextFile:
fileContentString = currentTextFile.read()
fileContentList = [line for line in fileContentString.split('\n') if line.strip()]
print(fileContentString)
print(fileContentList)
with textFile.with_name(textFile.name+"noemptylines").open(mode="w", encoding="utf8") as currentTextFile:
for line in fileContentList:
currentTextFile.write(f"{line}\n")