Tim
Tim

Reputation: 3

How do I open a .txt file for data storage in Python?

I really would like to store some variables in a .txt file (or something else, if necessary) to be able to use them again even after closing the python terminal.

I've also tried to create the file before I append to it: dat = open("data22", "x") but that didn't solve the problem...

n = "hello"
dat = open("data22.txt", "a")
dat.write(n)
dat.close()

my full code is here:

import colorama
from colorama import init, Fore
colorama.init()
while True:
    e = input( "--> ")
    while "n" in str(e):
        e = e.replace("n", str(n))
        print("   ", e)
    if e.find("v") == 0:
        n = round(((float(e[1:]))**(1/2)), 10)
        print(Fore.LIGHTBLUE_EX + str(n) + Fore.RESET)
    elif e.find("b") == 0:
        n = ((float(e[1:]))**(2))
        print(Fore.LIGHTBLUE_EX + str(n) + Fore.RESET)
    elif "v" in str(e):
        n = round(((float(e[(e.find("v") + 1):]))**(1/(float(e[:(e.find("v"))])))), 10)
        print(Fore.LIGHTBLUE_EX + str(n) + Fore.RESET)
    elif "b" in str(e):
        n = ((float(e[(e.find("b") + 1):]))**(float(e[:(e.find("b"))])))
        print(Fore.LIGHTBLUE_EX + str(n) + Fore.RESET)
    else:
        print(Fore.LIGHTRED_EX + "please define if you want to square or pull the root from your number (%s), by typing n 'v' for root or n 'b' for square..." % e)
        print("examples:    3v%s  --> (cubic-root of %s)" % (e, e))
        print("             2b%s  --> (square of %s)" % (e, e) + Fore.RESET)
    dat = open("data22.txt", "a")
    dat.write(n)
    dat.close()

The problem is, that the file "data22.txt" doesn't even appear in the file explorer.

Upvotes: 0

Views: 192

Answers (2)

Saleem Ali
Saleem Ali

Reputation: 1383

Just open file with a+ mode it will open exist file else will create new for you.

dat = open("data22.txt", "a+")

Also you may want to open the file outside while loop to avoid file opening and closing every time.

dat = open("data22.txt", "a+")
while True:
    ...
    dat.write(n)

dat.close()

More Pythonic

open file using with for safely file closing

with open("data22.txt", "a+") as dat:
    while True:
        ...
        dat.write(n)

And most important

You must add condition for break statement in while loop to not to fall into infinite loop

while True:
    ...
    if condition:
        break

Upvotes: 0

Brizar
Brizar

Reputation: 131

with open(..., 'a') you only append to a file, but can not create it. So you may need to check if the file exists and only then append, and create it otherwise.

See Writing to a new file if it doesn't exist, and appending to a file if it does for more details

if os.path.exists(filename):
    data = open("data22.txt", "a")  # append if already exists
else:
    data = open("data22.txt", "w")  # make a new file if not

Upvotes: 1

Related Questions