我有時會收到一個.ini文件修改和刪除值之後,看起來像這樣:如何清理configparser文件中的空行?
[Section A]
x = 1
d = 2
[Section B]
a = 3
有一種簡單的方法來保持它的清潔和去除部分之間的空行?
我有時會收到一個.ini文件修改和刪除值之後,看起來像這樣:如何清理configparser文件中的空行?
[Section A]
x = 1
d = 2
[Section B]
a = 3
有一種簡單的方法來保持它的清潔和去除部分之間的空行?
也許這可以工作:
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版本,也許你c一個使用此代碼以提高性能:
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()
只需使用SED:
sed '/^$/d' myfile.ini
工作
我從來沒有聽說過SED。它是基本python庫的一部分嗎? – Dima
可能是'-i'工作到位。 –
@Dima:它是一個標準的Unix工具,如果你在Linux或OS X上,它默認安裝。 –
如果你想使用一個嚴格的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)
爲什麼不能寫入沒有%:n_lines = [如果line.strip()]爲行的行,則爲 – Dima
是的,您可以在沒有'%' – kip
的情況下獲得'line'的值。如果在每個部分之後留下一條空白行,這將是完美的,但我可以想象這會更復雜一點。也許如果它將每個「[」替換爲「\ n [」除了第一個「[」 – Dima