2017-04-25 16 views
0

我有時會收到一個.ini文件修改和刪除值之後,看起來像這樣:如何清理configparser文件中的空行?

[Section A] 
x = 1 
d = 2 



[Section B] 
a = 3 

有一種簡單的方法來保持它的清潔和去除部分之間的空行?

回答

0

也許這可以工作:

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() 

Reference

+0

爲什麼不能寫入沒有%:n_lines = [如果line.strip()]爲行的行,則爲 – Dima

+0

是的,您可以在沒有'%' – kip

+1

的情況下獲得'line'的值。如果在每個部分之後留下一條空白行,這將是完美的,但我可以想象這會更復雜一點。也許如果它將每個「[」替換爲「\ n [」除了第一個「[」 – Dima

0

可能更容易使用的工具,像grep

$ grep -v "^\\s*$" foo > bar 

但如果你有使用Python然後檢查this answer

+0

它只是似乎不可思議的是,configparser模塊用來不保留INI文件整齊自身。 – Dima

+0

@Dima:這將是一個很酷的功能。 – fiacre

+0

並不是說我有這樣的技能,但將這樣的功能添加到官方configparser庫會有多難? – Dima

0

只需使用SED:

sed '/^$/d' myfile.ini

工作

+0

我從來沒有聽說過SED。它是基本python庫的一部分嗎? – Dima

+0

可能是'-i'工作到位。 –

+0

@Dima:它是一個標準的Unix工具,如果你在Linux或OS X上,它默認安裝。 –

1

如果你想使用一個嚴格的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)