[SOLVED] Opening a .txt file in python for name generator

Issue

This Content is from Stack Overflow. Question asked by Sean

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.



Solution

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

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


This Question was asked in StackOverflow by Sean and Answered by user9468014 It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?