mardi 27 août 2019

How to solve if-statement being ignored by Python?

So I just wanted to make a code that scans the current directory for text files and deletes them if both word count and file size (specified by user) are not met (pardon the untidiness as this is still a draft code).

There are two if-statements (commented in code) that does not seem to run the print function even when there is nothing in the delete_list dictionary variable (Which means len(delete_list) == 0). Any idea why? No errors are produced.

Tried tinkering with the code and realized that while the else condition is being recognized, this is not the case for the if-statement.Seems like I can narrow down problem to len(delete_list) condition. As far as I know, I believe that I used proper syntax for len(delete_list) and if-statement. Please tell me if I am wrong.

import os

file_list = []
words = 0
size = 0
lines = 0
deleted_list = {}
remaining_list = {}

for file in os.listdir(os.getcwd()):
    if file.endswith(".txt"):
        file_list.append(file)

user_word_count = int(input("Please enter word limit: "))
user_file_size = int(input("Please enter file size limit (bytes): "))

for file_name in file_list:
    fr = open(file_name, 'r')
    size = os.stat(file_name).st_size
    for line in fr:
        words_list = line.split()
        lines = lines + 1
        words = words + len(words_list)
    if words > user_word_count and size > user_file_size:
        deleted_list[file_name] = [words, size]
        os.remove(file_name)
    else:
        remaining_list[file_name] = [words, size]

print("The following lists the deleted text files: ")

#This is where the if-statement is ignored:
#print not returning anything for some reason

for file2 in deleted_list:

    if len(deleted_list) == 0:
        print("N/a")
    else:
        print(file2, "[word count, file size]:",deleted_list[file2])


print("The following lists the non-deleted text files: ")

# Similar problem with if-statement here:

for file3 in remaining_list:

    if len(remaining_list) == 0:
        print("N/a")
    else:
        print((file3, "[word count, filesize]:",remaining_list[file3]))

Expecting if-statement and print to return "N/a", but don't get anything returned. Do note that there are no error messages.

Aucun commentaire:

Enregistrer un commentaire