简体   繁体   中英

Python updating text files

Hi guys i'm making a manager software on python and I came across a problem I made a an original text file for my software that contains all my data.Now i have an options of 'add' to the data in the software, but I want the data added by the users to go to a separate text file and not disturb the original. Anyone know how? My code:

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

You need to write the updated text into another file.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM