python - Pandas 错误:“NoneType”对象没有属性“head”
问题描述
我是 python 特别是熊猫库的新手。这是我的代码。
file_path = "C:\\Users\\Roshaan\\Desktop\\"
b = os.listdir(file_path)
f = 1
for file in b:
def func():
print("format not supported")
#prints file name i.e test.csv
print(file)
path = file_path + file
df = pd.read_csv(path) if file.endswith(('.csv', '.tsv')) else func()
print (df.head(1))
这是我面临的错误。
AttributeError: 'NoneType' object has no attribute 'head'
解决方案
这是因为,正如评论中提到的,func()
没有返回任何东西。因此,当文件不以.csv
or结尾时.tsv
, df 实际上是 None。
要解决此问题,您可以执行以下操作:
file_path = "C:\\Users\\Roshaan\\Desktop\\"
b = os.listdir(file_path)
for file in b:
#prints file name i.e test.csv
print(file)
path = file_path + file
if file.endswith(('.csv', '.tsv')):
df = pd.read_csv(path)
print (df.head(1))
else:
print("format not supported")