2013-08-22 68 views
0

我使用的東西像一個字符串添加X零:由蟒蛇

tmp=fileA.read(4) 
outfile.write(tmp) 

但問題來了,如果的fileA在到達終點,只有2個字節的離開了。在這種情況下,TMP的內容將是

xx (Not XXXX any more) 

而且我想通過0來補償缺失的X,所以它可以像

xx00 

當我寫到文件OUTFILE

的問題是,我知道我可以使用函數

len(tmp) 

知道我需要多少個0添加,有沒有簡單的方法做這個添加操作?

我能想到的

if len(tmp) == 2 : tmp = tmp + "00" 
elif len(tmp) == 3: ....... 

但這是某種「笨」的方法。

有沒有辦法做到這一點,如:

tmp << (4-len(tmp)) | "0000" 

感謝您的幫助

+0

你能描述一下你正試圖解決的*實際問題嗎? –

+0

可能重複的[用空格填充python字符串?](http://stackoverflow.com/questions/5676646/fill-out-a-python-string-with-spaces) – Oli

回答

2

check out simp其中'1.txt'包含一些字節數據,我們每個都讀取4個字節。

fp1 = open("1.txt", "r") 
fp2 = open("2.txt", "w") 

while True: 
    line = fp1.read(4).strip() if not line: # end of file checking   break 
    # filling remaining byte with zero having len < 4 
    data = line.zfill(4)[::-1] 
    print "Writting to file2 :: ", data 
    fp2.write(line) 
fp1.close() 
fp2.close() 
+0

這不是反向數字嗎?就像fp1.read(4)是32,結果是2300? – Jblasco

+0

您應該在打開文件或其他方式時嘗試使用with語句,除非最終阻止才能安全關閉文件流。 –

8

海峽有你正在嘗試做一個函數:

tmp=fileA.read(4) 
tmp.ljust(4, '0') 
outfile.write(tmp) 

例如:

'aa'.ljust(4, '0') => 'aa00' 
+0

這就是我想要的。非常感謝 – thundium

+0

歡迎您:) –

+1

+1我正在建議'(tmp +'0000')[:4]',不知道'ljust'。 – chepner