6

Is there a way to check if a text file is empty in Python WITHOUT using os ?

What I have tried so far

x = open("friends.txt")
friendsfile = x.readlines()

if friendsfile == None 

But I don't think it's the correct way.

Lukaku
  • 83
  • 1
  • 1
  • 8
  • why can't you use the os? – Radan Apr 15 '16 at 14:34
  • The solution is in the link given by @Andy. Duplicate confirmed. – David Guyon Apr 15 '16 at 14:36
  • 2
    No i dont think there is a solution at that link, please note he does not wanna use os. – Radan Apr 15 '16 at 14:38
  • 1
    Its memory intensive to open the file to check if it's empty, if all you want is to check if the file is empty. if the file is already open, then you can use the answer from the link provided by Andy. – Radan Apr 15 '16 at 14:39
  • 1
    Note that your solution could be fixed to become correct if you changed `if friendsfile == None` to `if friendsfile == []` (`[]` is the empty list, and `readlines` returns a list) or just `if not friendsfile` (since `[]` is treated as false). However the given answer is definitely more efficient. – Alex Hall Apr 15 '16 at 15:24

1 Answers1

11

Not sure why you wouldn't use os, but I suppose if you really wanted you could open the file and get the first character.

with open('friends.txt') as friendsfile:
    first = friendsfile.read(1)
    if not first:
        print('friendsfile is empty')
    else:
        #do something
miradulo
  • 28,857
  • 6
  • 80
  • 93
  • with open('friends.txt') as friendsfile: if friendsfile == []: print('friendsfile is empty') else: #do something ....... gives you the same with one line less – mrk May 25 '18 at 14:57
  • wrong answer. if the first line is just a new line and nothing else on the file. it counts as one which is true – greendino Jun 05 '20 at 00:49
  • @AbdullahSaid as it should? – miradulo Jun 05 '20 at 06:49