Pandas Error: 'NoneType' object has no attribute 'head'
Question:
I am new to python specially pandas library.This is my code.
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))
This is the error I am facing.
AttributeError: 'NoneType' object has no attribute 'head'
Answers:
This is because, as mentioned in the comments, the func()
is not returning anything. So when a file does not end with .csv
or .tsv
, df is actually None.
To fix this you can do the following:
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")
I am new to python specially pandas library.This is my code.
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))
This is the error I am facing.
AttributeError: 'NoneType' object has no attribute 'head'
This is because, as mentioned in the comments, the func()
is not returning anything. So when a file does not end with .csv
or .tsv
, df is actually None.
To fix this you can do the following:
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")