kingjhez
kingjhez

Reputation: 13

Going to a specific position in a file

I am fairly new to python. I have been doing a project that i have been struggling on recently and I'd be glad if i can receive some help.

I am conducting a programme in which will take an input from a user and see if the input is seen in the file. The input is a name tag, e.g. the user will have to type in a unique code like 't56700' and then the programme will see if the code is in the file. However, along with the code comes with other information.

What i need to do is to take in a user input, and if it's valid, i would need to jump to where that input is located on the file and print the code (the name tag) along with all the information with it.

The file looks like this:

nametag,x,x,x

nametag,x,x,x

nametag,x,x,x

^ Several lines of this

This is my code so far, I'm trying to get to where the user's input is seen on the file and print the info along with it.

file = open("filetest.txt","r").readlines()


nametag = input ("What is your name tag?")

if nametag in open('filetest.txt').read():

    with open('filetest.txt', 'r') as searchfile:

        for line in searchfile:
                    if nametag in line:



                        print ("nametag: " + nametag)
                        print ("xxxx ", line[2])
                        print("xxxx:",line[3])
                        print("xxxx:",line[1])
                        print("xxxx:",line[4])

                        break 

The numbers within the square brackets like 'line[2]' for example only take me to the start of the file and not the location at where i want the file to read from.

Upvotes: 0

Views: 50

Answers (1)

mhawke
mhawke

Reputation: 87134

First of all, you don't need to open and read the file three times - once will suffice.

The data appears to be in CSV format so you can use the csv module to help parse the file.

import csv

nametag = input("What is your name tag?")

with open('filetest.txt') as searchfile:
    reader = csv.reader(searchfile)
    for row in reader:
        for row[0] == nametag:
            print("nametag: {}".format(nametag))
            print("xxxx: {}".format(row[2]))
            print("xxxx: {}".format(row[3]))
            print("xxxx: {}".format(row[1]))
            break    # if you want the first one only

This assumes that the file contains 4 columns of data as shown in your sample. Remember that column numbers start from 0.

If you don't want to use the csv module, you can use str.split() to a similar effect:

with open('filetest.txt') as searchfile:
    for line in searchfile:
        row = line.split(',')
        for row[0] == nametag:
            ...

Upvotes: 2

Related Questions