jeudi 28 février 2019

Break program if file is empty

The code below picks a random word from a file and later delete the word and its working great. I want the program to BREAK when file is empty since I delete every random word picked from the file.

Here is Random part of the code:

import random
import os

g = r"C:\Users\Homer\name.txt"
lines = [line.rstrip('\n') for line in open(g)]
rand = random.choice(lines)       
print(rand)

Is it good to say Break if file is empty and print "file is empty"? Or if Random (rand) return no word, then break and print file is empty.

I have already checked this site and there are some answers on how to check if a file is empty and print file empty or file size is zero or there is not word in file. However, I could find one that say BREAK program if file is empty. I get the error below when my file is empty.

--->rand = random.choice(lines)
IndexError: Cannot choose from an empty sequence

At the moment I'm using the code below to check if file is empty or not. but i keep getting error with the break statement.

if os.path.getsize("name.txt") == 0:
    print("File is Empty")
else:
    print("File is not Empty")
    break


 ----> SyntaxError: 'break' outside loop




Aucun commentaire:

Enregistrer un commentaire