Search code examples
pythonfileflaskfile-read

How to extract information from a txt(RIS) file in flask


my file looks in a text editor like the following:

Firstname  - phil
Lastname  - taylor
Birthdayyear  - 1956
Country  - england
END  -

I stored the file in my python variable txtFileand when I print the file using print(txtFile.read()) it looks like the following in the console:

b'Firstname  - phil\r\nLastname  - taylor\r\nBirthdayyear  - 1956\r\nCountry  - england\r\nEND  - '

And now I need to get the firstname, lastname, birthday year and country and store these information in variables so that I later can access the information.

So for example when I print("His first name is " + firstName) I'll get His first name is phil in the console.

The schema of the txt file is not always the same. The names like "Firstname","Lastname", "Birthdayyear" and "Country" are always the same but they are not always in the same order. So it could be that for example "Country" is the first line and "Firstname" is the last line.

I havent found a problem which is the same as mine is on stackoverflow, so maybe someone can help me out with this problem.

Thanks a lot


Solution

  • Finally I found a solution for the problem. I don't know, if this is the best way to do but it works for me:

    First I went through every line of the txt file and added every line to an array. Then I splitted every line of the array when there was a " - " in the line. That splits every line for example from ["Firstname - phil"] to ["Firstname","phil"] and then you can access the name if you go through every line of the array and make an if request: if the first element of the line is equal to "Firstname", set your firstName variable equal to the second element of this line. I don't know if this is understandable, but here's how it looks like in python code... :-D

     txtFileToArray = []
     splittedTxtArray = []
     firstName=""
    
         #go through every line of the text file
         for line in txtFile:
    
              #put every line at the end of the array txtFileToArray and delete the "b" (binaray) at the beginning of every line
              txtFileToArray.append(line.decode('utf-8'))
    
        #then go through every line of the array and split every line when there is a "  - " and store the lines in a new array
         for line in txtFileToArray: 
    
              splittedTxtArray.append(element.split("  - "))
    
        #then check every line of the splitted array if there is a Firstname at the first position
        for linein splittedTxtArray:
    
              if(line[0] == "Firstname"):
                 firstName= line[1]
    

    I hope this can help you someday :-)