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

Time:01-08

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?

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 . . .

CodePudding user response:

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. :-)

CodePudding user response:

In file2.txt you have "Username " and "Password " with space in the end before ":". So "Username " != "Username" and "Password " != "Password"

  • Related