[英]Python updating text files
大家好,我正在 python 上制作管理器软件,我遇到了一个问题,我为我的软件制作了一个包含我所有数据的原始文本文件。现在我可以选择“添加”到软件中的数据,但是我希望用户添加到 go 的数据到单独的文本文件中,并且不会干扰原始文件。 有谁知道怎么做? 我的代码:
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()```
您需要将更新后的文本写入另一个文件。
# 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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.