0

Here is my code:

classs = input("Class [1, 2 or 3] -  ")

if classs =='1':
        name = ).read():
                print ("True")
                break
            else:
                print ("False")

So basically, I need the program to find the content 'name' in the .txt file and what comes along with it (same line)

If 'Tom' (name) was in the .txt file and 'Tom' was in-putted as the 'name' the program would output True. As the name was found within the .txt file.

My question is how do i output the contents found under name, which will then allow me to use the integers to output an average score.

KryptoModz
  • 13
  • 6
  • You may want to read the Input Output help section of the python documentation at https://docs.python.org/3/tutorial/inputoutput.html You should be verifying that the document opened correctly and reading the content from the file, parsing the content to determine if it is contains the name your looking for. – Brian Cain Oct 21 '15 at 19:53
  • Yes everything is working and the program does read the contents within the text file and if the condition of 'name' was met it outputs 'True'. However I would like the program to output the condition 'name' which was in the text file. If the content was found. – KryptoModz Oct 21 '15 at 19:55
  • See the load_numbers() function at https://en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_2.6/File_IO –  Oct 21 '15 at 19:58
  • "the program does read the contents within the text file"--I would suggest that you print "line" after the "for line in datafile" statement as that line has nothing to do with reading the file. Also you are reading the entire file and you want to examine each line within the file instead. Saying that it is working to someone who is trying to help will reduce your chances of help next time. –  Oct 21 '15 at 20:01
  • if it's not nescessary to have it in a txt-file, see my answer – palsch Oct 21 '15 at 20:04
  • Briefly, my task is to make a Maths quiz for student and there name and score out of 10 must be saved into a .txt file. The second task is to allow the user to input there name and the program must find the 3 latest scores of the user and make an Average of there score. So i want python to be able to get the specific users score and print it. So i can then use the numbers to create an average score. – KryptoModz Oct 21 '15 at 21:27

3 Answers3

0

I would recommending using the with construct as it handles the close for you. The following program loops through all lines in the file looking for the name in the contents read

with open('1.txt', "r") as fp:
   data = fp.readline()
   while data != "":
      if name in data:
         print ("True")
            break
      else:
          print ("False")
      data = fp.readline()
Brian Cain
  • 946
  • 1
  • 7
  • 20
  • Note that your readline is outside the while loop. Also, it will print True or False for every record. You possibly only want to print False if the name was not found any where in the file. –  Oct 21 '15 at 20:10
  • Good catch on the indent. I left the False in the code to closer match the original poster's code. You are correct however that It can be removed or added to a while else statement. – Brian Cain Oct 21 '15 at 20:12
0

It could look something like this:

classs = input("Class [1, 2 or 3] -  ")

if classs =='1':
    name = input("What is your name? -  ")

    datafile = '1.txt'
    found = False

    # This is a better way to open the file, closes when done
    with open(datafile, 'r') as f:
        data = f.readlines()
        for line in data:
            if name in line:
                print("True")
                found = True
        if found == False:
            print("False")

Hope this helps!

McGlothlin
  • 2,059
  • 1
  • 15
  • 28
  • Alright, what i want to know is when the program outputs 'True' it obviously met the condition inputted as the 'name' I want to know how can i output the condition form the .txt file into python? – KryptoModz Oct 21 '15 at 21:12
  • I'm not sure I understand. Are you trying to output the name variable to the screen? – McGlothlin Oct 21 '15 at 21:15
  • The text file has data such as 'John = 10/10.' So if the user puts in 'John' as there username the program will search for the term 'John' in the .txt file. If it comes as positive it outputs 'True' on python. If not then 'false'. I want to be able to print 'John = 10/10' via python if the program first meets the condition of 'John' being in the text file in the first place. I'm sorry im a noob at this and bad at explaining code. please forgive me. – KryptoModz Oct 21 '15 at 21:24
  • No worries! I would either print the entire line if that's the ONLY thing on the line, or use the `re` module to find that with a regular expression. You know it's on that particular line because of the `line` variable in the loop. If you wanted to search the entire file without scanning line by line, then `re` is the way to go. – McGlothlin Oct 21 '15 at 21:25
  • Yes thats what i need! If the user's username is 'John' and the program finds data corresponding to that string it should print everything in that line into python. In this case 'John = 10/10' I'm stuck on actually printing the key line i need to create an average score. – KryptoModz Oct 21 '15 at 21:29
  • so try `print(line)` and the output will be 'John = 10/10' in this case. – McGlothlin Oct 21 '15 at 21:31
  • Great that works! What if the term 'John' was found multiple times in the text file. Is there anyway to output all the lines that include 'John'! If so then great I can proceed with my task! – KryptoModz Oct 21 '15 at 21:35
  • This will output each line for all lines that contain 'John' if you put the `print(line)` statement in the `if name in line` condition. – McGlothlin Oct 21 '15 at 21:36
  • Thank you! You have helped me so much, i can thank you enough. I will encounter many problems in the future and was wondering if there a better way in contacting you? You have a massive help thanks, a lot of stress has been pulled away from my shoulders! – KryptoModz Oct 21 '15 at 21:40
  • Happy to help! Actually, it's better to ask questions here on SO so everyone can see and contribute. I just joined the site. So long as your question is clear and concise, you will find countless people willing to help. Check out past questions, too. Any time I need to do something new in Python, this site is my hero. – McGlothlin Oct 21 '15 at 21:44
  • I am currently undergoing a few more problems? Care if I explain? I'm just a little shy as you have already helped me so much! – KryptoModz Oct 21 '15 at 21:50
  • You should ask a separate question, or google "python foo" where foo is the thing you are trying to do, otherwise this thread will get really confusing. – McGlothlin Oct 21 '15 at 21:52
  • Alrighty i'll create another thread! Thanks for your time and effort in helping me. – KryptoModz Oct 21 '15 at 21:53
0

First, to read the content of a file, use

content = ""
with open("yourfile.txt", "r") as f:
    for s in f: content += s

Here you can find more information on with.

So, you have the content of the file in the variable content. Now your question is a bit unclear. The first part is clear, only write

if name in content:

... but what is the format of the file?

but...

If you want to save scores of users in a dictionary in a file, it's a better option to use pickle. So first you import pickle:

import pickle

...and you have a dictionary like

{"Tom":10, "Pascal":12}

in the variable scores, you save it with

pickle.dump(scores, open("myfile.p", "wb"))

and read it with

scores = pickle.load(open("myfile.p", "rb"))

See this examples and the Python dok.

Community
  • 1
  • 1
palsch
  • 5,528
  • 4
  • 21
  • 32