我正在尝试将随机生成的数字添加到文本文件中,因为我将一个文件中的名称读入另一个文件中。 这是我的代码:
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()
当前,dogswrite文本文件正在读取,并且每个文本都换行:
Molly
Dave
Tim
我希望文件读为
Molly, 1 , 30, 48, 100
然后换一行。 戴夫和蒂姆也是如此。 感谢您的所有帮助。
类代码:
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()
答案 0 :(得分:1)
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)返回一个随机整数N,使得a <= N <= b。 randrange(a,b + 1)的别名。
这基本上意味着,如果您的范围是(7,42),那么end并不是排他性的,因为7和42都是包含性的,即它们可以成为结果的一部分。
>>> random.randint(0,1)
1
>>> random.randint(0,1)
0
>>> random.randint(0,1)
1
>>> random.randint(0,1)
1
请勿将其与我们用于for循环的正常范围(开始,结束)混淆,在该范围中,结束是排他的。
>>> list(range(0,1))
[0]
>>> list(range(0,2))
[0, 1]
str.join(可迭代) 返回一个字符串,该字符串是可迭代的字符串的串联。如果存在任何非字符串,则会引发TypeError 可迭代的值,包括字节对象。之间的分隔符 elements是提供此方法的字符串。