Tee Jones Tee Jones - 3 months ago 8x
Python Question

How do i get my code to print one character name on seperate lines 10 times?

Ok so I'm writing a code that generates ten Dungeon and dragons characters. I need to generate ten characters, their should be one character on each line. Here's the instructions from my teacher:
"Modify the program to generate 10 names and store them in an array. Then Write a function, dumpFile that writes the array to a file called "CharacterNames.txt" There should be one Character Name on each line in the file."

So here's my original code.

import random

def main():

txt1 = loadFile("names.txt")
name_txt1 = random.randint(0, len(txt1))
name2_txt1 = random.randint(0, len(txt1))
txt2 = loadFile("titles.txt")
titles_txt2 = random.randint(0, len(txt2))
txt3 = loadFile("descriptors.txt")
descriptors_txt3 = random.randint(0, len(txt3))

print(txt2[titles_txt2], txt1[name_txt1], txt1[name2_txt1],"the", txt3[descriptors_txt3])

def loadFile(fileName):

array = []
file = open(fileName, "r")

for line in file:


Here's my modified code so far.

import random

def main():
txt1 = loadFile ("names.txt")
txt2 = loadFile ("titles.txt")
txt3 = loadFile ("descriptors.txt")
array = []

for _ in range (10):
name_txt1 = dumpFile2 (txt1)
name2_txt1 = dumpFile2 (txt1)
titles_txt2 = dumpFile2 (txt2)
descriptors_txt3 = dumpFile2(txt3)
x = " ".join ((titles_txt2, name_txt1, name2_txt1, "the", descriptors_txt3))
array.append (x.strip())
dumpFile (array)

def loadFile (fileName):
with open (fileName) as file1: return file1.read ().splitlines ()

def dumpFile (arr):
file = open ("CharacterNames.txt", "w")

def dumpFile2(arr):
return arr [random.randint(0, len(arr)- 1)]


Here's the output I'm getting from my modified code:This image shows the output I am getting from my modified code. I'm getting a bunch of lines when I'm supposed to only generate ten character names with one on each line


dumpfile is called in each iteration of your loop. Put it after the loop instead. In addition (as I'm sure you know), you are not reading to the file dumpfile, only printing to terminal.

You could do something like

names = '\n'.join(arr)

before closing the file.