Python在文本文件中找不到第二行

问题描述 投票:0回答:2

我有问题。当我搜索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
2个回答
0
投票

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

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


0
投票

我对您的程序进行了一些更改:

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)

当然,此代码不会遇到您遇到的问题。有一些评论可以解释这些更改。

让我知道您是否有任何疑问或不清楚的地方:)

© www.soinside.com 2019 - 2024. All rights reserved.