0

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'
farhan jatt
  • 509
  • 1
  • 8
  • 31

1 Answers1

1

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")
Mohammad
  • 3,276
  • 2
  • 19
  • 35
  • Thanks but i wanted to use the ternary expression for some reason. – farhan jatt Jul 31 '21 at 16:04
  • 1
    That would make the code really unreadable. But you can write something like: `print(pd.read_csv(path).head(1) if file.endswith(('.csv', '.tsv')) else "format not supported" )` – Mohammad Jul 31 '21 at 16:17