Search code examples
pythonpython-3.xplaintext

How do I read a random character from a plain text file


I do not know how to read a random character from a text file, and would like to learn how.

This is what happened when I started messing around with python! I know I will be doing something like this later on in school so I am practising. Reading a line would not suffice as you will see - I am open to tips and just a straight answer as I realise my code is very sloppy. The Raspberry Pi with this code on is running Raspbian lite with a few bits extra installed (a gui, idle), and runs python 3.5.3.

I write some of these to a text file:

f = open("selected.txt","w")
chars = 'abcdefghijklmnopqrstuvwxyz'
ucchars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
smbls = '`¬!"£$%^&*()-_=+{[}]:;@~#<,>.?'
nos = '1234567890'
space = ' '

Like this:

usechars = input('Use lower case letters? answer y or n.')
if usechars == 'y':
    f.write(chars)
useucchars = input('Use upper case letters? answer y or n.')
if useucchars == 'y':
    f.write(ucchars)
usesmbls = input('Use symbols? answer y or n.')
if usesmbls == 'y':
    f.write(smbls)
usenos = input('Use numbers 0-9? answer y or n.')
if usenos == 'y':
    f.write(nos)
usespace = input('Use spaces? answer y or n.')
if usespace == 'y':
    f.write(space)

I would like to print a selected amount of random characters from the text file and print it in the shell, but I do not know how to get a random single character from a text file. If there would be a better way of doing it (probably the case) or you need more code please tell me. Thanks in advance.

UPDATE here is the code:

f.close()
with open("selected.txt","r") as f:
    contents = f.read
random_character = random.choice(contents)
for i in range(amnt):
    password = ''
    for c in range(length):
        password += random_character
    print(password)

Solution

  • If the file is not very large an easy way to pick a random character is to read it into a string first, then just select a random character from the string:

    import random
    
    with open("selected.txt", "r") as f:
        contents = f.read()  # NOTE the () after read
    
    random_character = random.choice(contents)
    print("The random character I've chosen is: ", random_character)
    

    If you'd like to create a string with random choices you can use your for loop, but you have to choose a new random character inside the loop:

    with open("selected.txt","r") as f:
        contents = f.read()
    
    password = ''
    for i in range(amnt):
        random_character = random.choice(contents)
        for c in range(length):
            password += random_character
    print(password)