#python #text-files
Вопрос:
Привет, ребята, я создаю программное обеспечение для управления на python, и я столкнулся с проблемой, я создал оригинальный текстовый файл для своего программного обеспечения, который содержит все мои данные.Теперь у меня есть опция «добавить» к данным в программном обеспечении, но я хочу, чтобы данные, добавленные пользователями, отправлялись в отдельный текстовый файл и не нарушали оригинал. Кто-нибудь знает, как это сделать? Мой код:
stock_file = open('A3_s3899885_stock.txt', 'a')
print("Adding Movie")
print("================")
item_description = input("Enter the name of the movie: ")
item_genre = input("Enter the genre of the movie:")
item_quantity = input("Enter the quantity of the movie: ")
item_price = input("Enter the price of the movie: ")
stock_file.write(item_description ' ,')
stock_file.write(item_genre ', ')
stock_file.write(item_quantity ', ')
stock_file.write(item_price)
stock_file.close()
user_choice = int(input('Enter 7 to continue or 8 to exit: '))
if user_choice == 7:
menu()
else:
exit()```
Комментарии:
1. Напишите другой файл
open('Users.txt', 'w')
2. Написать новый текстовый файл?!? поэтому измените имя файла по дате и времени. отредактируйте — предложение PCM еще лучше — настройте его по имени пользователя, который вводит данные.
3. Вот что, измените имя аргумента open()
Ответ №1:
Вам нужно записать обновленный текст в другой файл.
# read original data
original_file_path = 'A3_s3899885_stock.txt'
stock_file = open(original_file_path, 'r')
original_data = stock_file.read()
stock_file.close()
# add user data into user_data
user_data = original_data
print("Adding Movie")
print("================")
item_description = input("Enter the name of the movie: ")
item_genre = input("Enter the genre of the movie:")
item_quantity = input("Enter the quantity of the movie: ")
item_price = input("Enter the price of the movie: ")
user_data = item_description ' ,'
user_data = item_genre ' ,'
user_data = item_quantity ' ,'
user_data = item_price ' ,'
# save user_data into file
user_file_path = ''
user_stock_file = open(user_file_path, 'w')
user_stock_file.write(user_data)
user_stock_file.close()
user_choice = int(input('Enter 7 to continue or 8 to exit: '))
if user_choice == 7:
menu()
else:
exit()