I sometimes get an .ini file that looks like this after changing and deleting values:
[Section A]
x = 1
d = 2
[Section B]
a = 3
Is there an easy way to keep it clean and remove those blank lines between the sections?
If you want to use a strictly python solution, you can create a temp file, copy over the non empty lines, and then replace the file.
from tempfile import mkstemp
from os import close
from shutil import move
def replace(filename, name, new_value):
fd, path = mkstemp()
with open(path,'w') as tmpfile:
with open(filename) as csv:
for line in cvs:
if line.strip()!="":
tmpfile.write(line)
close(fd)
move(path, filename)
Probably easier using a tool like grep
$ grep -v "^\\s*$" foo > bar
but if you have to use Python then check out this answer.
Just use sed:
sed '/^$/d' myfile.ini
works
Maybe this can work:
lines = open("file").readlines()
n_lines = ["%s" % line for line in lines if line.strip()]
f = open("file", "w")
f.write("".join(n_lines))
f.close()
I use the list comprehension and create a new variable with the filter lines.
EDIT
If you can add a linebreak for each section, this maybe can work:
lines = open("file").readlines()
n_lines = ["\n%s" % line if "[Sect" in line else line for line in lines if line.strip()]
f = open("file", "w")
f.write("".join(n_lines).lstrip())
f.close()
EDIT 2:
I'm not sure... but
If your file is so large and the Python that you work is 3 version, maybe you can use this code for better performance:
def readfile(filepath):
with open(filepath, "r") as f:
for line in f:
yield line
lines = readfile("file")
n_lines = ["\n%s" % line if "[Sect" in line else line for line in lines if line.strip()]
f = open("file", "w")
f.write("".join(n_lines).lstrip())
f.close()