Techmaster
Techmaster

Reputation: 41

Get information from 2 txt file together

I've 2 txt file feedback.txt and student.txt. feedback.txt contains information like:

101---Great!!!---5.0---100114 
feedback_id---feedback---rating---training_id # I've like 1000 lines info in this txt file 

student.txt contains information like:

30317998---ernst_hsieh---eh30---Ernst---https://i.jpg---EH---101
student_id---name---password---title---user_image---initials---feedback_id) # 1000 lines info in this txt file  

Now, if I want to print out the feedback based on the student_id where do I start? Not sure how can I compile 2 txt and get information

Here's what I've tried:

with open ('feedback.txt') as feedback_txt: 
    read_feedback = feedback_txt.read().split('---') 
with open('student.txt') as studednt_txt: 
    read_student = student_txt.read().split('---') 
#Then I don't know 

Upvotes: 1

Views: 75

Answers (1)

Edward
Edward

Reputation: 150

I would suggest reading the files and storing them in dictionaries using the ids as keys

# read feedback.txt
with open("feedback.txt", "r") as f:
    lines = f.read().splitlines()
    feedback = {
        feedback_id: [feedback, rating, training_id]
        for feedback_id, feedback, rating, training_id in [
            line.split("---") for line in lines if line.count("---") == 3
        ]
    }

# print(feedback)
# {'101': ['Great!!!', '5.0', '100114']}

# read student.txt
with open("student.txt", "r") as f:
    lines = f.read().splitlines()
    students = {
        student_id: [name, password, title, user_image, initials, feedback_id]
        for student_id, name, password, title, user_image, initials, feedback_id in [
            line.split("---") for line in lines
        ]
    }

# print(students)
# {'30317998': ['ernst_hsieh', 'eh30', 'Ernst', 'https://i.jpg', 'EH', '101']}

student_id = input("Enter your student ID: ")
# Enter your student ID: 30317998


student_feedback = feedback[students[student_id][5]]

print(f"{students[student_id][0]}'s feedback: {student_feedback[0]}")
# ernst_hsieh's feedback: Great!!!

Upvotes: 2

Related Questions