【问题标题】:Python Can't find the second line in text filePython在文本文件中找不到第二行
【发布时间】:2019-11-29 20:23:30
【问题描述】:

我有问题。当我搜索 ID 时,信息只出现在文本文件的第一行。但是当搜索不在第一行的另一个ID时,找不到它

import random
def create_sup():
    with open("supplier.txt","a+") as file:
        sup_name = input("Enter New Supplier's Name : ")
        sup_idgen = random.randint(0,9999)
        sup_id = sup_idgen
        print("Supllier ID : ",sup_id)
        sup_city = input("Enter New Supplier's City : ")
        sup_contact = int(input("Enter New Supplier's Contact Number : "))
        sup_email = input("Enter New Supplier's Email : ")
        columnsup = [sup_name,sup_id,sup_city,sup_contact,sup_email]
        file.write(str(columnsup)+"\n")


def s_searchbyid():
    with open("supplier.txt","r") as file:
        data = file.readline().split("\n")
        id = input("Enter Supplier ID : ")
        for line in data:
            if id in line:
                print(line)

【问题讨论】:

  • 你是想把变量写成一个列表,还是用逗号隔开更好?

标签: python list text-files


【解决方案1】:

readline 方法只读取一行。在您的情况下,您读取一行并根据换行符 '\n' (没有)将其拆分,因此您最终得到的是一个元素列表。

使用data = file.read().split("\n")

【讨论】:

    【解决方案2】:

    我对你的程序做了一些修改:

    import random
    
    
    def create_sup():
        sup_name = input("Enter New Supplier's Name: ")
        sup_idgen = random.randint(0, 9999)
        sup_id = sup_idgen
        print("Supplier ID : ", sup_id)
        sup_city = input("Enter New Supplier's City: ")
        sup_contact = int(input("Enter New Supplier's Contact Number: "))
        sup_email = input("Enter New Supplier's Email: ")
        # Only open file when necessary.
        with open('supplier.txt', 'a') as file_1:
            file_1.write(f'{sup_name}, {sup_id}, {sup_city}, {sup_contact}, {sup_email}\n')
    
    
    def s_searchbyid():
        sup_id = input("Enter Supplier ID : ")
        # Only open file when necessary.
        with open('supplier.txt', 'r') as file_1:
            # Iterate over the lines of the file. Yes, it's that simple!
            for line in file_1:
                if sup_id in line:
                    print(line)
    

    当然,这段代码不存在您所面临的问题。有几个 cmets 可以解释这些变化。

    如果您有任何问题或不清楚的地方,请告诉我:)

    【讨论】:

      猜你喜欢
      • 2013-08-27
      • 2019-08-23
      • 2021-06-22
      • 2019-05-03
      • 1970-01-01
      • 1970-01-01
      • 2018-01-21
      • 2012-04-06
      • 2018-03-02
      相关资源
      最近更新 更多