Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to extract data from file and assign each data to each variables on python?

So i wannna know the solution from my question. I already tried this

import re


username = ""
password = ""
full_name = ""
birth_date = ""
phone_number = ""
address = ""


with open("file2.txt", "r") as f:
    contents = f.read()

lines = contents.split("\n")
for line in lines:
    if ": " in line:
        key, value = re.split(":\s*", line)
        
        if key == "Username":
            username = value
        elif key == "Password":
            password = value
        elif key == "Nama Lengkap":
            full_name = value
        elif key == "Tanggal Lahir":
            birth_date = value
        elif key == "Nomor HP":
            phone_number = value
        elif key == "Alamat":
            address = value

print(username)
print(password)
print(full_name)
print(birth_date)
print(phone_number)
print(address)

But the output is not what i expected. The username and password value not appearing, here when i run it



kjdaskd
10-20-1000
+218112301231
dsajh
Press any key to continue . . .

It just printing 2 line of blank or whitespace. How to solve this?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

This is inside file2.txt

Username : dsadj
Password : 12345
Nama Lengkap: kjdaskd
Tanggal Lahir: 10-20-1000
Nomor HP: +218112301231
Alamat: dsajh

This is the output that i expect:

dsadj
12345
kjdaskd
10-20-1000
+218112301231
dsajh
Press any key to continue . . .

>Solution :

The empty lines come from your variables username and password not being updated from their initial empty string.

Due to the extra whitespace in your source file, your equality checks fail since you’re testing if "Username " == "Username": which is never true (notice the extra whitespace).

Change it to this to allow zero or more whitespace before the colon:

key, value = re.split("\s*:\s*", line)
#                      ^^^

Outputs:

dsadj
12345
kjdaskd
10-20-1000
+218112301231
dsajh

Alternatively, change your source file to always have no white-space before colons – it will have the same effect. 🙂

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading