Mateusz Broncel
Mateusz Broncel

Reputation: 29

How to make if statement on empty list in python

I have a small problem with creating an if statement in python. I am compering two csv files using Panda Library and I want to create an if statement which will be checking if list is empty. So this is my code

file1 = pd.read_csv('otomotofirst.csv')
file2 = pd.read_csv('otomotonew.csv')

change=(file2[~file2.Linki.isin(file1.Linki)])

if change is None:
    break
else:
    send_mail(subjectNew,change)

It is working quite well, however if it is empty (or in my case None) email is also sent. Of course it sends an empty list but it doesn't break.

I was trying do it with True and False statement but this error always pop ups

ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()

Upvotes: 1

Views: 642

Answers (2)

Diogo Lopes
Diogo Lopes

Reputation: 84

You may use os.path.getsize() in order to obtain the size of a file. So, if you wnat to check if your file is empty:

filesize = os.path.getsize("file.csv")
filesize1 = os.path.getsize("file1.csv")

def file_compare():
  if(filesize == 0 and filesize == 0):
      print("Both files are empty")
  if(filesize == filesize1):
      print("File sizes are equal", str(filesize)
  else:
      print(str(filesize))
      print(str(filesize1))`

Hope it works!

Upvotes: 0

ALollz
ALollz

Reputation: 59549

You don't have a list, you have a DataFrame. DataFrames, even empty, are not None.

pd.DataFrame() is None
False

You check if a DataFrame is empty with the empty attribute.

pd.DataFrame().empty
True

Regarding the error, you can't treat a DataFrame like a list to check emptiness

if []: print(True)              # Works 
if pd.DataFrame(): print(True)  # ValueError

The code should be

if change.empty:
    break
else:
    send_mail(subjectNew, change)

Upvotes: 2

Related Questions