天天看點

AttributeError: 'NoneType' object has no attribute 'format'

今天寫代碼的時候出現了一個及其簡單的問題,百度很久都沒找到是什麼原因,最後才發現是print 函數少了個括号。

# -*- encoding:utf-8 -*-
from csv import reader


# Load a CSV file
def load_csv(filename):
    file = open(filename, "r")
    lines = reader(file)  # 此時reader傳回的值是csv檔案中每行的清單,将每行讀取的值作為清單傳回
    dataset = list(lines)  # 把filename檔案傳回的疊代的器對象lines清單化
    return dataset


filename = 'pima-indians-diabetes.csv'
dataset = load_csv(filename)
#  少括号輸出
# print('加載檔案 {0} 有 {1} 行 {2} 列').format(filename, len(dataset), len(dataset[0]))
# 正确輸出
# print(('加載檔案 {0} 有 {1} 行 {2} 列').format(filename, len(dataset), len(dataset[0])))
           

然後就出現了下面的:

AttributeError: ‘NoneType’ object has no attribute ‘format’

問題

D:\dev\python.exe "D:/pycharm/code/statisticsLearning/Load _CSV_File.py"
Traceback (most recent call last):
  File "D:/pycharm/code/statisticsLearning/Load _CSV_File.py", line 15, in <module>
    print('加載檔案 {0} 有 {1} 行 {2} 列').format(filename, len(dataset), len(dataset[0]))
AttributeError: 'NoneType' object has no attribute 'format'
加載檔案 {0} 有 {1} 行 {2} 列

           
在python3當中是需要print()才能輸出
#錯誤代碼
print('加載檔案 {0} 有 {1} 行 {2} 列').format(filename, len(dataset), len(dataset[0]))
           

希望對有此疑惑的人有所幫助