2017-02-01 9 views
0

В основном, что я хочу сделать, так это показать список заметок в python, чтобы пользователь мог видеть, что находится в списке, не открывая файл. Я сделал это. Теперь я хочу, чтобы пользователь вводил желаемый продукт и сохранял его, а также распечатывал продукт и цену. Это то, что текстовый файл выглядит следующим образом:Сбор пользовательского ввода. Чтение и запись в текстовые файлы в python

000,67463528,50mm bolts,2.20 
001,34512340,plain brackets,0.50 
002,56756777,100mm bolts,0.20 
003,90673412,l-shaped brackets,1.20 
004,45378928,normal brackets,0.80 
005,1638647,10mm bolts,0.10 
006,14372841,plain brackets,1.29 
007,29384754,200mm bolts,0.50 
008,12345768,screwdriver,10.99 

До сих пор я могу добавить продукты в конце кода, и я могу вставить текст в определенный номер строки. Я разрабатываю, как распечатывать квитанцию ​​на основе ввода пользователем. Я новичок в python, рассматривая это как хобби, любая помощь была бы весьма признательна. Благодаря!

Это код питона:

def search(): 
    gtin = input("What is the GTIN code? ") 
    des = input("What is the name of the product? ") 
    price = input ("What is the price of the product? ") 
    position_str = input("What line do you want this inserted at? ") 
    print("This is the list now: ") 
    position = int(position_str) 

    with open("task2.txt", "r") as a_file: 
     data = a_file.readlines() 

    data.insert(position, "00" + position_str + "," + gtin + "," + des + "," + price + "\n") 

    data = "".join(data) 

    with open("task2.txt", "w") as a_file: 
     a_file.write(data) 

    input() 

    with open('task2.txt','r')as Task2: 
     print('{0:<19}  {1:<19}  {2:<19}  {3:<19}'.format("\nNo.","GTIN-8","Item Name","Price")) 
     for row in Task2: 
      row=row.strip() 
      eachItem=row.split(",") 
      print('{0:<19}  {1:<19}  {2:<19}  {3:<19}'.format(eachItem[0],eachItem[1],eachItem[2],eachItem[3])) 
    print() 



def add(): 
    print("The data you put here will be added onto the end ") 
    gtin = input("What is the GTIN-8? ") 
    des = input("What is the description? ") 
    price = input("What is the price? ") #gets all the info they want to add 
    print("This is the list now: ") 

    with open("task2.txt","a") as a_file: 
      a_file.writelines(" ," + gtin + "," + des + "," + price + "\n") 
      a_file.close() 
      print("Product has been added") 

    with open('task2.txt','r')as Task2: 
     print('{0:<19}  {1:<19}  {2:<19}  {3:<19}'.format("\nNo.","GTIN-8","Item Name","Price")) 
     for row in Task2: 
      row=row.strip() 
      eachItem=row.split(",") 
      print('{0:<19}  {1:<19}  {2:<19}  {3:<19}'.format(eachItem[0],eachItem[1],eachItem[2],eachItem[3])) 
    print() 



def reciept(): 

    print() 



#this is the menu. this is where the user will make choices on what they do 

def menu(): 
    print("What would you like to do?") 

    with open('task2.txt','r')as Task2: 
     print('{0:<19}  {1:<19}  {2:<19}  {3:<19}'.format("\nNo.","GTIN-8","Item Name","Price")) 
     for row in Task2: 
      row=row.strip() 
      eachItem=row.split(",") 
      print('{0:<19}  {1:<19}  {2:<19}  {3:<19}'.format(eachItem[0],eachItem[1],eachItem[2],eachItem[3])) 
    print() 


    print("1. Add a product onto a specific line number?") 
    print("2. Or add a product onto the end?") 
    print("3. Buy products and have them printed onto a reciept?") 
    choice=int(input("Which one?: ")) 
    if choice==1: 
     search() 
    elif choice==2: 
     add() 
    elif choice==3: 
     reciept() 

menu() 
+0

Если это ответили на ваш вопрос, пожалуйста, примите ответ. – SirJames

ответ

0

Что исправить и места документации

Во-первых, я не могу показаться, чтобы повторить то, что вы делаете так, я работал до моего собственное решение в некоторой степени ...

Если вы предоставили текстовый документ с информацией в нем, это может помочь при отладке.

Это в сторону ... Я заметил, что если у вас нет файла «task2.txt», у вас нет способа его создать.

Это можно сделать с помощью Task2 = open("task2.txt", "w"). Input/Output Documentation for Python 2.7

Во-вторых, некоторые из форматирования могут быть улучшены с помощью выражений; И.Е.,

\t [Закладка],

\n [перевод строки],

\r [возвращение],

Таким образом, вы можете выполнять PEP-8 стандартных правил. PEP-8 Documentation

Хорошо, так что это не в порядке, то, что вам нужно сделать дальше, - это понимать разные между открытыми и открытыми ... Не слишком большая разница здесь, за исключением того, что с открытыми заставляет вас немедленно перейти в цикл , Если документ не содержит в нем информации, вы получите ошибку (это проблема, которую я имею прямо сейчас).

Хранение его в виде списка (task2 = open ([file], 'r') лучше, поскольку оно позволяет вам использовать его позже. Вы также должны запустить проверку, чтобы увидеть, существует ли файл ...

Пример

в-третьих, вот несколько советов, п»фокусы:

import os 

boolCheckOnFile = os.path.isfile("[Location to File]\\task2.txt") 
# Check if it exists 
if boolCheckOnFile==False: 
    # Create file, "w" for write 
    task2Creation = open("[Location to File]\\task2.txt", "w") 
    # Close the file to reopen and read it or write to it... 
    task2Creation.close() 

# Again "w" for write, "a" for append, "r" for read, "r+" for read/write... 
task2 = open("[Location to File]\\task2.txt", "r+") 

Отсюда, вы можете записать в файл, приняв str.write(information) Но это всегда лучше, чтобы закрыть файл, когда. вы на самом деле файл ... Таким образом, внесенные вами изменения являются постоянными str.close().

Слова советов, print() # print "()", you must fill it, so at least do a newline, like so:

print("\n")

Что я сделал, чтобы исправить некоторые начинающие вопросы

Наконец, ниже моя итерация исправленной версии (для только части меню вашего сценарий) ...

def menu(): 

    print("What would you like to do?") 

    # Check if file exists 
    if os.path.isfile('C:\\users\\[username]\\Desktop\\task2.txt')==False: 
     # Create it and promptly close it, so it is in the correct location 
     task1 = open('C:\\users\\[username]\\Desktop\\task2.txt','w') 
     task1.close() 

    # Open for read-write 
    task2 = open('C:\\users\\[username]\\Desktop\\task2.txt','r+') 

    # splits for new line break, making an array 
    info = task2.read().split("\n") 

    # Check to see if the file is empty 
    if len(info) is not 0: 
     print('{0:<19}  {1:<19}  {2:<19}  {3:<19}'.format("\nNo.", 
                    "GTIN-8", 
                    "Item Name", 
                    "Price")) 
     # Read each line of document 
     for line in info: 
      arrayOfItems = line.split(",") 
      print('{0:<19}  {1:<19}  {2:<19}  {3:<19}'.format(arrayOfItems[0], 
                     arrayOfItems[1], 
                     arrayOfItems[2], 
                     arrayOfItems[3])) 

    else: 
     print('You have no items listed!') 

    print("\n") 


    print("1. Add a product onto a specific line number?") 
    print("2. Or add a product onto the end?") 
    print("3. Buy products and have them printed onto a reciept?") 
    choice=int(input("Which one?: ")) 
    if choice==1: 
     search() 
    elif choice==2: 
     add() 
    elif choice==3: 
     reciept() 

menu() 

Удачи вам и насладитесь создание скриптов и программ на Python! Иногда это весело и сложно. Я когда-то был на твоем месте, просто помни, что тебе стало легче, когда ты продолжаешь работать над этим.

ТАКЖЕ:

Проверьте некоторые другие Stack Overflowers работает ... Иногда простое решение, как это может быть решен, глядя на некоторых других народов работать и вопросы ...

Opening file for both reading and writing

Basic read and write

Lowercase examples plus reading and writing

Copying files for modifying documents and creating saves