【发布时间】:2017-09-23 02:45:00
【问题描述】:
我有时会在更改和删除值后得到一个如下所示的 .ini 文件:
[Section A]
x = 1
d = 2
[Section B]
a = 3
有没有一种简单的方法可以保持干净并删除部分之间的那些空白行?
【问题讨论】:
标签: python
我有时会在更改和删除值后得到一个如下所示的 .ini 文件:
[Section A]
x = 1
d = 2
[Section B]
a = 3
有没有一种简单的方法可以保持干净并删除部分之间的那些空白行?
【问题讨论】:
标签: python
如果你想使用严格的 python 解决方案,你可以创建一个临时文件,复制非空行,然后替换文件。
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)
【讨论】:
也许这可以工作:
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()
我使用列表推导并使用过滤器行创建一个新变量。
编辑
如果您可以为每个部分添加换行符,这也许可以工作:
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()
编辑 2:
我不确定……但是
如果你的文件很大,而你使用的 Python 是 3 版本,也许你可以使用这个代码来获得更好的性能:
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()
【讨论】:
% 的情况下获得line 的值
.write()中lstrip()的第一个换行符,你可以测试代码并确认..
【讨论】:
只需使用 sed:
sed '/^$/d' myfile.ini
有效
【讨论】: