Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/bin/env python3
- if __name__ == "__main__":
- # a stands for append mode, meaning that everything written
- # will be added to the end of the file
- with open("products.txt", "a") as f:
- # go to the end of the file.
- # if the file is epmty, we are at the beginning of the file,
- # otherwise we add lines to the end of the file.
- # seek(offset[, whence])
- # The default value for whence is SEEK_SET. Values for whence are:
- # SEEK_SET or 0 – start of the stream (the default); offset should be zero or positive
- # SEEK_CUR or 1 – current stream position; offset may be negative
- # SEEK_END or 2 – end of the stream; offset is usually negative
- absolute_pos = f.seek(0, 2)
- if absolute_pos == 0:
- # if end of file is actually the beginning of the file:
- # add a header
- # \t is a tab character, \n is a newline character indicating a linebreak
- f.write("id\tname\tprice\n")
- while True:
- try:
- # if the conversion from input string to int or float fails,
- # an exception is raised by python, that we catch
- product_id = int(input("Please enter the product id: "))
- product_name = input("Please enter the product name: ")
- # in some regions a decimal comma is used instead of a decomal point
- product_price = input("Please enter the product price: ").replace(",", ".")
- product_price = float(product_price)
- except Exception as e:
- # catches any exception raised
- #print(e) # you can print what kind of errors are raised if you want to see for yourself
- print("An error occurred, please enter the product again.")
- # goes back to the beginning of the loop and retries the input process
- # here you could add a prompt, whether the user wants to actually continue
- # and if not, you break free from the while loop.
- continue
- line_to_append_to_file = f"{product_id}\t{product_name}\t{product_price}\n" # needs python >= 3.6
- #line_to_append_to_file = "{id}\t{name}\t{price}\n".format(id=product_id,name=product_name, price=product_price) # works with python >= 3.0
- # write tab separated information to file
- f.write(line_to_append_to_file)
- print("Appending: ", line_to_append_to_file)
- confimation = input("Do you want to enter another product?[Y/n]: ")
- # removes whitespace and newline characters if there are any before or after the input string
- confimation = confimation.strip()
- if confimation == "" or confimation.lower() == "y":
- # simply "enter"/"newline" or "Y"/"y" will allow to enter another item
- continue
- else:
- # anything else will abort the while loop.
- break
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement