【问题标题】:How do I open a .txt file for data storage in Python?如何在 Python 中打开 .txt 文件进行数据存储?
【发布时间】:2020-03-07 02:00:53
【问题描述】:

我真的很想将一些变量存储在 .txt 文件(或其他文件,如有必要)中,以便即使在关闭 python 终端后也能够再次使用它们。

我还尝试在附加文件之前创建文件: dat = open("data22", "x") 但这并没有解决问题...

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

我的完整代码在这里:

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()

问题是,文件“data22.txt”甚至没有出现在文件资源管理器中。

【问题讨论】:

  • 您是否尝试使用numpyPandas 库打开它?

标签: python


【解决方案1】:

使用 open(..., 'a') 你只能追加到一个文件,但不能创建它。因此,您可能需要检查文件是否存在,然后才追加,否则创建它。

详情请见Writing to a new file if it doesn't exist, and appending to a file if it does

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

【讨论】:

  • open(path, 'a') 将创建文件,如果它不存在,检查是没有必要的,检查甚至不好(你应该总是做一个尝试,除了处理文件时,因为其他一些进程可以在检查和调用之间进行干预),如果可能,您还应该使用上下文管理器 iewith open('foo.boo', 'a') as file:
【解决方案2】:

只需使用a+ 模式打开文件,它将打开现有文件,否则将为您创建新文件。

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

此外,您可能希望在while 循环之外打开文件,以避免每次打开和关闭文件。

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

dat.close()

更多 Pythonic

使用with打开文件以安全关闭文件

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

最重要的是

您必须在while 循环中为break 语句添加条件,以免落入infinite loop

while True:
    ...
    if condition:
        break

【讨论】:

  • print("非常感谢")
猜你喜欢
  • 2017-05-13
  • 1970-01-01
  • 2019-07-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-10
相关资源
最近更新 更多