-2

It's obvious I'm doing something wrong, but I can't find help online as to why. I want to create an if function that prints out that the inputted file contains no data. When I run this and request an empty.txt file, it skips straight to the else: and I get

Enter name of file: empty.txt

In the terminal, instead of the printed result, I'm asking for.

 # Ask user to input file, open and and read file

userinput = input('Enter name of file: ')

userfile = open(userinput)

data = userfile.read()

#if file is empty print "x contains no data"

if data is None:
    print(userinput + ' contains no data.')
else:
    print(data)

userfile.close()
HIMANSHU PANDEY
  • 684
  • 1
  • 10
  • 22
Filth
  • 1

1 Answers1

0
 # Ask user to input file, open and and read file

userinput = input('Enter name of file: ')

userfile = open(userinput)

data = userfile.read()

#if file is empty print "x contains no data"
if len(data) == 0:
    print(userinput + ' contains no data.')
else:
    print(data)

userfile.close()

this works, because read an empty file returns an empty string "", you can check it by condition len(data) == 0

Xi Gou
  • 49
  • 2
  • 2
    Actually you can just use `if not data:` because an empty string is considered False, unlike any other string. – Mark Ransom Oct 24 '22 at 01:24