在遷移到python3和rhel8時,我們需要維護一個遺留應用程式。
因此,我們必須創建一個向后兼容的版本。
有一個讀取 csv 的函式。
在python3中,我們有這個:
from io import StringIO
import csv
def read_csv(filename):
"""
Sanitise and read CSV report
"""
# lowest number of columns to expect in the header
sane_columns = 7
# temporary sanitised CSV
stream = StringIO()
with open(filename, encoding="utf-8") as csvfile:
reader = csv.reader(csvfile)
temp_writer = csv.writer(stream)
for csv_row in reader:
if len(csv_row) >= sane_columns:
temp_writer.writerow(csv_row)
# Move stream back to the start
stream.seek(0)
dict_reader = csv.DictReader(stream)
return dict_reader
在python2上,這給出了以下錯誤:
TypeError: unicode argument expected, got 'str'
然后我們更改代碼以在 python2 中作業:
from io import BytesIO
import csv
def read_csv(filename):
"""
Sanitise and read CSV report
"""
# lowest number of columns to expect in the header
sane_columns = 7
# temporary sanitised CSV
stream = BytesIO()
with open(filename) as csvfile:
reader = csv.reader(csvfile)
temp_writer = csv.writer(stream)
for csv_row in reader:
if len(csv_row) >= sane_columns:
temp_writer.writerow(csv_row)
# Move stream back to the start
stream.seek(0)
dict_reader = csv.DictReader(stream)
return dict_reader
但是在python3上它給出了這個錯誤:
TypeError: a bytes-like object is required, not 'str'
我們如何重構將在兩個版本的 python(2.7 和 3.6 )上運行的函式
需要決議的 csv 有一些垃圾行,這里是一個示例:
some
garbage
lines
Client Name,Policy Name,Status Code,Job Start Time,Job End Time,Job Status,Schedule Name,Schedule Type
xxxxx,WN4_VMWARE_3M,0,"Nov 28, 2021 9:07:38 PM","Nov 28, 2021 9:38:38 PM",Successful,DI3M,Differential Incremental
yyyyyy,WN4_VMWARE_3M,0,"Nov 28, 2021 9:04:52 PM","Nov 28, 2021 9:30:38 PM",Successful,DI3M,Differential Incremental
作為額外的挑戰。我不能使用六庫。不允許在服務器上安裝 pip 包:(
uj5u.com熱心網友回復:
我會使用這種方法來檢測安裝了哪個版本,如果是一個版本,則執行某些操作,如果不是,則執行其他操作:
import sys
print(sys.version_info[0])
if sys.version_info[0] < 3:
#block of code
else:
#block of code
uj5u.com熱心網友回復:
我不確定正確的解決方案。然而,我們曾經遇到過類似的問題,我們提到的編碼格式是“utf-8”,但是一位同事使用 Excel 保存檔案,將檔案轉換為其他格式,此后第二個錯誤開始彈出。嘗試以正確的 csv 格式保存檔案。和平!
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/378310.html
上一篇:在串列上迭代日期時間函式
