Попытка загрузить список, который я сохранил в текстовый файл в python - PullRequest
0 голосов
/ 19 июня 2020

У меня есть сценарий, который выводит некоторые списки в текстовый файл, но как мне получить python для загрузки текстового файла при повторном запуске сценария? Код и пример текстового файла ниже

dates = []
rpay = 10.1

while True:
    x = input("How many hours did you work today?: ")
    if x == "":
        break # exit the loop
    try:
        x = float(x)
    except ValueError:
        print ("Not a valid number. Try again.")
        continue
    hours.append(x)
    print(hours)
    a = input("Enter the month: ")
    b = input("Enter the day: ")
    c = input("Enter the year: ")
    print(a + "/" + b + "/" + c)
    dates.append(a + "/" + b + "/" + c)

thours = sum(hours)
pay = thours * rpay

print(f"You have worked {thours} hours")
print(f"You have made approximately ${pay:.2f}")

with open("hours.txt", "w") as output:
    output.write(str(hours))
    output.write("""
""")
    output.write(str(dates))```

[3.0, 3.0]
['6/6/2020', '6/7/2020']

Ответы [ 3 ]

0 голосов
/ 19 июня 2020

Используйте стандарт, например JSON.

import json

...


with open("hours.txt", "w") as output:
    json.dump({'hours': hours, 'dates': dates}, output)

Позже, когда вы захотите прочитать его снова в

with open("hours.txt") as input:
    d = json.load(input)

hours = d['hours']
dates = d['dates']
0 голосов
/ 19 июня 2020

Вы можете использовать встроенный модуль, pickle:

import pickle

with open("hours.txt", "wb") as output: # Here is where we write the lists into the txt file
    pickle.dump([hours, dates], output)

with open("hours.txt", "rb") as output: # Here is where we extract the information dumped into the txt file
    hours, dates = pickle.load(output)
0 голосов
/ 19 июня 2020

Обычно для подобных задач я бы делал следующее:

Создаю метод загрузки:

def load_from_file(filename):
    with open(filename, 'r') as f:
         # Do whatever here
         content = f.readlines()
     return content

Затем метод сохранения:

 def save_to_file(filename, newContent):
      # save stuff here, I use append mode
      # you can also write oldContent + newContent as well
      with open(filename, 'a') as f:
           f.write(newContent)

Если вы хотите убедиться, что файл существует перед загрузкой:

try:
    with open(filename, 'r') as f:
        f.read()
 except FileNotFoundError:
     # Do whatever here, create the file for example
     open(filename, 'a').close()
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...