简体   繁体   English

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

[英]Python Can't find the second line in text file

I have a problem.我有个问题。 When I search for the ID, the information appears only on the first line of the textfile.当我搜索 ID 时,信息只出现在文本文件的第一行。 But when search for another ID that isn't on the first line, can't find it但是当搜索另一个不在第一行的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)

The readline method reads only one line. readline方法只读取一行。 In your case you read one line and split it based on newline '\\n' (there is none) so what you eventually end up with is a one element list.在您的情况下,您阅读一行并根据换行符 '\\n' (没有)拆分它,因此您最终得到的是一个单元素列表。

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

I made some changes to your program:我对您的程序进行了一些更改:

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)

Of course, this code does not have the problem you were facing.当然,这段代码没有你遇到的问题。 There are a few comments to explain the changes.有一些注释可以解释这些更改。

Let me know if you have any questions or if something is unclear :)如果您有任何问题或不清楚的地方,请告诉我:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM