简体   繁体   中英

looking for line and linenumber in text file

I'm making a extra function for my chat program which allows you to register by typing a specific command that makes the host script save your peername and a name you insert in the terminal, its saved like this 57883:Jack in a txt file (names.txt) on the host machine. if a number of people have registered it'll look like this

57883:jack 
57884:bob
57885:connor
57886:james
57887:zzhshsb93838
57887:ryan

when someone sends a message i want to know if his/her name is registered and if so, get the name to send to the client, so instead of seeing the peername the client will see the name of the person sending the message. in order to do that i need to know if the peername is in the file and if so; where in the file, in which line. i've got this so far:

 peer = sock.getpeername()
 with open('names.txt', 'r') as d:
     lines = d.readlines()
     for peer in lines:

and i don't know how to find out in which line it was found, and when i know that how to seperate 57883 and ack and select jack and save it. Cheers!

with open("names.txt", "r") as f:
    for i, line in enumerate(f):
        numb, name = line.rstrip().split(":")
        print i, numb, name

You can ask Python to provide a tuple of line number and line content for each line of the file (see enumerate(f) ). Then you remove the line terminator (see line.rstrip() ) and split the line to parts separated by the provided character (see split(":") ). You have all three components available then.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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