2015-04-29 46 views
0

我需要打開一個小但數量可變的文件,每個文件的行數都相同。然後我需要返回每個行的元組。我的代碼返回一個元組,但每個元素保留其'\ n';如何在它被壓縮到元組之前去除它?從多個同時打開的文件的行中刪除' n'

這是到目前爲止的代碼

files = ['file1', 'file2', 'file3'] 
fds = [ open(file) for file in files ] # gets all file open at same time 
read_fds = izip(*fds) 
for tpl in read_fds: 
    print tpl # will become a 'yield' stmt once the '\n' is sorted 
for fd in fds: 
    fd.close() 

我有一個測試組3個文件,每個具有5行,每一行表示文件號的行號。代碼打印這些測試文件的準確記錄。

('f1ln1\n', 'f2ln1\n', 'f3ln1\tthis\tthat\n') 
('f1ln2\n', 'f2ln2\n', 'f3ln2\tthis\tthat\n') 
('f1ln3\n', 'f2ln3\n', 'f3ln3\tthis\tthat\n') 
('f1ln4\n', 'f2ln4\n', 'f3ln4\tthis\tthat\n') 
('f1ln5\n', 'f2ln5\n', 'f3ln5\tthis\tthat\n') 

到目前爲止很好,但是如何在打包到元組之前從每一行剝離('\ n')?

我知道那裏有一個答案!尋找建議。謝謝&有一個美好的一天。

+0

很長的路要走每條線(逐行讀取) – Morb

回答

0

如何:

for tpl in read_fds: 
    templist = [] 
    for item in tpl: 
     templist.append(item.rstrip("\n")) 
    print tuple(templist) 

這將刪除字符串的右側任意換行符

+0

編輯,因爲我把這個元組當作字符串...現在修復 – Stefan

+0

@Stephan,謝謝 – bobox

1

您也可以使用字符串的切片

for tpl in read_fds: 
    list_stripped = [] 
    for s in tpl: 
     list_stripped.append(s[:-1]) 
    print tuple(list_stripped) 
+0

你犯了和我一樣的錯誤它是一個你正在操作的元組,而不是一個字符串。另外,如果文件末尾沒有換行符,那麼您的靈魂會截斷數據。 – Stefan

+0

編輯爲對字符串而不是元組進行操作。謝謝Stefan! –

0

我認爲最簡單的方法是將作業修改爲read_fds,以便從izip生成修改的元組:

read_fds = (tuple(s.rstrip() for s in tup) for tup in izip(*fds)) 

但是,我沒有測試過這個。