2017-04-03 53 views
0

我在Python中使用LZW算法編碼一個簡單的文本文件。但是,我意識到我只能使用write()函數將一個字符串寫入.txt文件,該函數佔用的空間幾乎相同。那麼是否有可能以某種方式將實際整數寫入文件(可能採用不同的格式),以實現正確的壓縮? ?將數字寫入文件而不是字符串進行數據壓縮?

readfile = open("C:/Users/Dhruv/Desktop/read.txt", "r") 
writefile = open("C:/Users/Dhruv/Desktop/write.txt", "w") 
content = readfile.read() 
length = len(content) 

codes = [] 
for i in range(0, 256) : 
    codes.append(str(chr(i))) 

current_string = "" 
for i in range(0, length) : 
    temp = current_string + content[i] 
    print(temp) 
    if temp in codes : 
     current_string += content[i] 
    else : 
     codes.append(current_string + content[i]) 
     writefile.write(str(codes.index(current_string)) + " ") 
     current_string = str(content[i]) 
writefile.write(str(codes.index(current_string)) + " ") 
readfile.close() 
writefile.close(); 
+0

你可能意思是*二進制文件*,用模式'wb'打開... –

+0

同意@AnttiHaapala,使用「wb」並用二進制編碼發送字節()。請參閱http://stackoverflow.com/questions/20955543/python-writing-binary – RobertB

+0

我想存儲大於255的整數,我該怎麼做?另外,我想僅以整數讀取它們 –

回答

1

如果數據可以被表示爲numpy的陣列,下面的函數可以在.txt文件寫爲整數:

import numpy as np 
def writer(_hd, _data): 
    out_file_name = str(_hd) + '.csv' 
    np.savetxt(out_file_name, _data, fmt='%i') 
    return None 

其中_hd是文件名和_data是numpy的陣列。 fmt ='%i'將數據保存爲整數;其他選項也可用here

相關問題