user3430541
user3430541

Reputation: 323

Random letter generator not working

Im having trouble figuring out how to write a script that basically saves a bunch of random letters to a .txt on different lines. What I have right now is:

import random
f = open("test.txt", "w") #clears current test.txt file
f.close()
f = open("test.txt", "a")
b = 0
def randomstring():
    global c
    valid_letters='abcdefghijklmnopqrstuvwxyz'
    c = ''.join(random.choice(valid_letters))
    

while b < 10000:
    randomstring()
    f.write(c + "/n")
    b = b + 1

f.close

What this outputs is

q/ne/ny/nt/nb/ng/nf/no/nu/ni/nr/nn/nh/nu/nr/ne/nx/nw/nr/nt/ns/nw/nk/nz/no/nb/nk/nh/nx/nj/nw/nu/no/nl/nv/nm/ni/nh/nd/nh/ng/nk/np/nd/na/no/nx/nn/ng/nb/np/nh/nb/nx/nj/nj/ne/nr/nb/nu/nr/nh/nj/nf/nw/ns/nl/np/nc/ne/nh/np/nu/nc/nw/nd/nt/nt/na/nk/np/nc/nm/nt/nt/nb/nw/nf/nf/nf/na/ni/n

What I want it to output is

q

e

y

t

ect. Thanks

Upvotes: 0

Views: 95

Answers (2)

Hugh Bothwell
Hugh Bothwell

Reputation: 56694

Here is a cleaned-up version:

# Assumes Python 3.x;
#  for Python 2.x, range should be replaced with xrange
from random import choice
from string import ascii_lowercase

OUTPUT = "test.txt"
NUM_WORDS = 10000
WORD_LENGTH = 1

def random_word(length, alphabet=ascii_lowercase):
    return ''.join(choice(alphabet) for i in range(length))

def main():
    with open(OUTPUT, "w") as outf:
        for i in range(NUM_WORDS):
            word = random_word(WORD_LENGTH)
            outf.write(word + "\n")

if __name__=="__main__":
    main()

Upvotes: -1

sshashank124
sshashank124

Reputation: 32197

You are escaping it incorrectly. The escape is as follows: \n not /n Escaping is done with backslashes not forward slashes.

As follows:

while b < 10000:
    randomstring()
    f.write(c + "\n")
    b = b + 1
f.close

q
e
y
t

Also, since you are clearing the file everytime you write to it, why not just open it as 'w' and write to it. That effectively overwrites the file, so it clears it and writes in it.

Upvotes: 4

Related Questions