Reputation: 19
I am trying to add numbers that are randomly generated into my text file as i read a name from one file into another. Here is my code:
def dogs():
total_cards = int(input("How many cards do you wish to play with? "))
N = int(total_cards)
Y = int(N/2)
Z = int(N/2)
with open("dogs.txt") as f: # Opens needed file
with open("dogswrite.txt", "w") as f1: # My own file for player names
for i in range(Y):
line_name = next(f).strip() # Lists the input number of results each on a new line
line_name = line_name + "\n"
f1.write(line_name)
with open ("dogswritecpu.txt", "w") as f2: # File for CPU names
for i in range(Z):
line_name = next(f).strip()
line_name = line_name + "\n"
f2.write(line_name)
dogs()
Currently the dogswrite text file reads with each being on a new line:
Molly
Dave
Tim
I want to the file to read as
Molly, 1 , 30, 48, 100
then a new line. The same happens to Dave and Tim. Thanks for all the help.
Class Code:
class Dog_card_player: #creates the class
def __init__(self,name):
self.name = name
self.exercise = exercise
self.friendliness = friendliness
self.intelligence = intelligence
self.drool = drool
def Card_stats_player(self): #creates the stats for the card
print("Name: " + self.name)
print("Exercise: " + self.exercise)
print("Friendliness: " + self.friendliness)
print("Intelligence: " + self.intelligence)
print("Drool: " + self.drool)
def Printing_card_player():
with open ("dogswrite.txt") as f1:
Dog_name_player = Dog_card_player(f1.readline())
Dog_name_player.Card_stats_player()
Upvotes: 0
Views: 91
Reputation: 814
import random
s= ', '.join(str(random.randint(1,100)) for i in range(4))
line_name = 'Molly'
line_name = line_name+', '+s+"\n"
print(line_name) # f1.write(line_name)
Output:
Molly, 42, 37, 39, 43
random.randint(a, b) Return a random integer N such that a <= N <= b. Alias for randrange(a, b+1).
What it basically means is that here end is not exclusive if your range is (7,42) both 7 and 42 are inclusive ie they can be part of result.
>>> random.randint(0,1)
1
>>> random.randint(0,1)
0
>>> random.randint(0,1)
1
>>> random.randint(0,1)
1
don't confuse it with normal range(start, end) that we use with for loop, in which end is exclusive.
>>> list(range(0,1))
[0]
>>> list(range(0,2))
[0, 1]
str.join(iterable) Return a string which is the concatenation of the strings in iterable. A TypeError will be raised if there are any non-string values in iterable, including bytes objects. The separator between elements is the string providing this method.
Upvotes: 1