![](/img/trans.png)
[英]What are the differences between these two methods of getting the union of 2 lists in Python?
[英]Python IO Gurus: what are the differences between these two methods?
我有兩種寫二進制文件的方法:第一種方法處理服務器接收的與文件上載相對應的數據(即,處理其enctype =“ multipart / form-data”的表單),第二種方法處理以電子郵件附件(即,通過使用get_payload()解析電子郵件正文獲得的文件數據)。
奇怪的是,它們不可互換:如果我使用第一個保存從電子郵件附件中解析的數據,它將失敗; 同樣,當處理上傳的文件數據時,第二個功能也會失敗。
關鍵區別是什么?
這是第一種方法:
def write_binary_file (folder, filename, f, chunk_size=4096):
"""Write the file data f to the folder and filename combination"""
result = False
if confirm_folder(folder):
try:
file_obj = open(os.path.join(folder, file_base_name(filename)), 'wb', chunk_size)
for file_chunk in read_buffer(f, chunk_size):
file_obj.write(file_chunk)
file_obj.close()
result = True
except (IOError):
print "file_utils.write_binary_file: could not write '%s' to '%s'" % (file_base_name(filename), folder)
return result
這是第二種方法:
def write_binary_file (folder, filename, filedata):
"""Write the binary file data to the folder and filename combination"""
result = False
if confirm_folder(folder):
try:
file_obj = open(os.path.join(folder, file_base_name(filename)), 'wb')
file_obj.write(filedata)
file_obj.close()
result = True
except (IOError):
print "file_utils.write_binary_file: could not write '%s' to '%s'" % (file_base_name(filename), folder)
return result
區別在於HTTP上傳方法(第一個)-接收文件狀對象本身(“ f”變量)作為其參數,並創建一個CGI模塊特定的“ read_buffer”以從該文件對象中分塊讀取數據到將它們復制到實際文件。
這在http上傳應用程序中很有意義,因為它將允許文件副本在仍上傳的情況下開始復制-我個人認為這並不重要,但對於上傳幾兆字節的情況,因為您的http響應將暫停直到所有上傳都通過一個簡單的CGI腳本完成。
另一種方法接收“ file_data”作為參數:所有要做的就是將此數據寫入新文件。 (另一個必須從類似文件的對象中讀取數據,並且它仍然為此創建一個中間對象)
您可以使用第二種方法保存HTTP數據,只需將其期望的對象類型作為其參數傳遞即可,因此,與其使用CGI字段值提供的“ f” strutmtn調用第二種函數,不如使用“ f.read()“-這將導致從“ f”文件中讀取所有數據(例如object),並從該方法查看相應的數據。
即:
#second case:
write_binary_file(folder, filename, f.read() )
第一個可能希望將類似文件的對象作為參數,從中讀取數據。 第二個期望該參數是一個包含要寫入的實際數據的字符串。
確保您必須查看read_buffer
函數的功能。
最明顯的區別是分塊讀取數據。 您沒有指定錯誤,但是我猜測在對read_buffer
的調用中,分塊方法失敗了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.