Opening a .txt file in python for name generator

Viewed 39

I am very new to python and just started to code some mini projects. Currently I am trying to create a code that picks a random first name from a .txt file and combines it with a random last name from a seperate .txt file. This is my code so far:

import random

firstname = "/Desktop/Python/Namelists/firstnames.txt"
firstnames = open(firstname, "rb").read().splitlines()

lastname = "/Desktop/Python/Namelists/firstnames.txt"
lastnames = open(lastname, "rb").read().splitlines()

name1 = random.sample(firstnames, 1)
name2 = random.sample(lastnames, 1)

name = name1 + name2

print(name)

I first tried to open the files without using "rb", but that gave me the following error:

UnicodeDecodeError: 'utf-8' codec can't decode byte 0x9f in position 1: invalid start byte

So I told python to read the files as binary. This works, but it gives me the output as a byte-string:

[b'Adam', b'Weber']

I want the output to be in plain text, every try to decode failed.

I am running Python 3.9.7 on MacOS Monterey. The .txt files are encoded in us-ascii.

EDIT: I use german names and so there are some special-characters such as "Ü, Ö and Ä".

2 Answers

You are reading the file in binary mode "rb". Try:

lastnames = open(lastname, "r").read().splitlines()

Code below is working but I think you set lastnames to "/Desktop/Python/Namelists/firstnames.txt" by mistake. If it's not, you can edit that in code.

import random

firstnames_file = open("/Desktop/Python/Namelists/firstnames.txt", "r")  # The file opened
firstnames = firstnames_file.read().split()  # It read file (type: list)

lastnames_file = open("/Desktop/Python/Namelists/lastnames.txt", "r")  # The file opened
lastnames = lastnames_file.read().split()  # It read file (type: list)

firstname = random.choice(firstnames)  # choosen a random value in the list
lastname = random.choice(lastnames)  # choosen a random value in the list

print(f"Name:{firstname}, Surname:{lastname}")

Note: Code works if in the txt file, every name has spaces between each other, like "Ben Emma Leon Mia" or "Ben (enter) Emma (enter) Leon (enter) Mia" (Sorry stack overflow don't allows adding line)

Related