简体   繁体   中英

python - reading txt file and checking if the file is empty

I have a file that is empty at the moment called Savings.txt I want this program to read the file and if the file is empty, call the user_balance function. If its not empty, then call the menu function.

this is what I have:

check = []    
with open('Savings.txt', 'r') as f: 
    pre_check = f.readlines()
    check = pre_check
    if not check:
        user_balance()
    else:
        menu()

When I run this, even though the file is empty, it goes to the menu function. What am I doing wrong?

Your so called empty file most likely has one single new line inside. So .readlines actually returns ['\n'] - which is indeed a truthy value.

If "empty", by your definition, means any file that has no contents ignoring whitespace - read the file and .strip its contents before performing the check

with open('Savings.txt', 'r') as f:
    content = f.read().strip()
    # Check if content is truthy/falsy

.strip will get rid of any leading or trailing whitespace (including newlines)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM