Search code examples
pythonpycharmsaveload

Cannot load or save txt. file


I wrote a code but apparently It does not save and load to my txt. file. I would greatly appreciate if you took a look into my code and told me what's wrong because I am having really hard time figuring it out myself. I didnt use pickle, as It was creating encoding related difficulties so I tried to find the other way around it and all which saves into my txt. file is "None". Thank you in advance.

def savedata(x):
    play_again = input("Are you willing to save existing progress? Y/N")
    if (play_again == "Y") or (play_again == "y"):
        print("Saving progress...")
        file = open('adam_malysz.txt', 'w')
        file.write(str(x))
        file.close()
        print("Your file has been called - adam_malysz.txt")
        print("Progress has been successfully saved.")
    else:
        print("Returning to main menu")
def arrayfancy():
    num1 = int(input("Select size of an array: "))
    value = []
    for i in range(num1):
        value.append(random.randint(1, 99))
    print("Printing data...")
    print(value)
    print("Sorting Array...")
    bubblesort(value)
    print(value)
    print("Average value is: ")
    print(statistics.mean(value))
    print("Minimum value is: ")
    print(min(value))
    print("Maximum value is: ")
    print(max(value))
    print("Your data has been successfully printed")

    if choice == 1:
       savedata(arrayfancy())


Solution

  • Your arrayfancy() has no return statement, so it returns None when it reach the end of the function block. savedata(x) then successfully write "None" to your file.

    You can add return value at the end of arrayfancy(), this will solve your issue.


    I tested the code bellow and I get the text file containing the array.

    def savedata(x):
        play_again = input("Are you willing to save existing progress? Y/N")
        if (play_again == "Y") or (play_again == "y"):
            print("Saving progress...")
            file = open('adam_malysz.txt', 'w')
            file.write(str(x))
            file.close()
            print("Your file has been called - adam_malysz.txt")
            print("Progress has been successfully saved.")
        else:
            print("Returning to main menu")
    
    def arrayfancy():
        num1 = int(input("Select size of an array: "))
        value = []
        for i in range(num1):
            value.append(random.randint(1, 99))
        print("Printing data...")
        print(value)
        print("Sorting Array...")
        bubblesort(value)
        print(value)
        print("Average value is: ")
        print(statistics.mean(value))
        print("Minimum value is: ")
        print(min(value))
        print("Maximum value is: ")
        print(max(value))
        print("Your data has been successfully printed")
        return value
    
    if choice == 1:
        savedata(arrayfancy())