收集用户输入。在python中读取和写入文本文件

时间:2017-02-01 16:28:45

标签: python file-handling

基本上我想要做的是在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的新手,研究这是一个爱好,任何帮助将不胜感激。谢谢!

这是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()

1 个答案:

答案 0 :(得分:0)

需要修复的内容和文档位置

首先,我似乎无法复制你正在做的事情,我在某种程度上制定了我自己的解决方案......

如果您提供了包含其中信息的文本文档,则可能有助于调试。

除此之外...... 我注意到,如果你没有&#34; task2.txt&#34;创建的文件,你没有办法创建一个。

可以使用Task2 = open("task2.txt", "w")完成此操作。 Input / Output Documentation for Python 2.7

其次,使用表达式可以改善一些格式; I.E.,

\t [tab],

\n [换行符],

\r [返回],

因此,您可以遵守PEP-8标准规则。 PEP-8 Documentation

好吧,这样就可以了,你接下来需要做的是理解开放和开放之间的不同......这里没有太多区别,除了开放迫使你立即跳入一个循环。如果文档中没有信息,则会导致错误(这是我现在遇到的问题)。

将其存储为列表(task2 = open([file],&#39; r&#39;)更好,因为它允许您以后使用它。您还应该运行检查以查看文件是否存在...

示例

第三,这里有一些提示n&#39;招数:

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脚本和程序!有时候这很有趣,也很有挑战性。我曾经在你的鞋子里,只要记住你继续努力就会变得更容易。

ALSO

查看其他一些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