我需要这个函数输出到.txt文件,我在它下面的内容只返回最后一行整数。
def random_grid(file):
grid = []
num_rows = raw_input("How many raws would you like in your grid? ")
num_columns = raw_input("How many columns would you like in your grid? ")
min_range = raw_input("What is the minimum number you would like in your grid? ")
max_range = raw_input("what is the maximum number you would like in your grid? ")
for row in range(int(num_rows)):
grid.append([])
for column in range(int(num_columns)):
grid[row].append(random.randint((int(min_range)),(int(max_range))))
for row in grid:
x = (' '.join([str(x) for x in row]))
print x
with open(r"test.txt", 'w') as text_file:
text_file.write(x)
如果用户选择3乘3网格,则可以打印低数量的1和9的高数字。
1 2 3
4 5 6
7 8 9
我只是
7 8 9
在我输出的.txt文件中
答案 0 :(得分:3)
open
,w
的第二个选项将覆盖文件的内容。请改为使用a
进行追加,但也要在每行后添加换行符\n
。
def random_grid(file):
grid = []
num_rows = raw_input("How many raws would you like in your grid? ")
num_columns = raw_input("How many columns would you like in your grid? ")
min_range = raw_input("What is the minimum number you would like in your grid? ")
max_range = raw_input("what is the maximum number you would like in your grid? ")
for row in range(int(num_rows)):
grid.append([])
for column in range(int(num_columns)):
grid[row].append(random.randint((int(min_range)),(int(max_range))))
for row in grid:
x = (' '.join([str(x) for x in row]))
print x
with open(r"test.txt", 'a') as text_file:
text_file.write(x)
text_file.write("\n")
另一种更有效的方法是将文件编写代码移到循环之外,如下所示:
def random_grid(file):
grid = []
num_rows = raw_input("How many raws would you like in your grid? ")
num_columns = raw_input("How many columns would you like in your grid? ")
min_range = raw_input("What is the minimum number you would like in your grid? ")
max_range = raw_input("what is the maximum number you would like in your grid? ")
for row in range(int(num_rows)):
grid.append([])
for column in range(int(num_columns)):
grid[row].append(random.randint((int(min_range)),(int(max_range))))
x = ""
for row in grid:
x += (' '.join([str(x) for x in row])) + "\n"
print x
with open(r"test.txt", 'w') as text_file:
text_file.write(x)
答案 1 :(得分:3)
您需要附加到文件而不是覆盖它
更改
with open(r"test.txt", 'w') as text_file:
到
with open(r"test.txt", 'a') as text_file:
用于追加模式
或将with open(r"test.txt", 'w') as text_file:
移到for row in grid
循环
import random
def random_grid(file):
grid = []
num_rows = int(raw_input("How many rows would you like in your grid? "))
num_columns = int(raw_input("How many columns would you like in your grid? "))
min_range = int(raw_input("What is the minimum number you would like in your grid? "))
max_range = int(raw_input("What is the maximum number you would like in your grid? "))
for _ in range(num_rows):
grid.append([random.randint(min_range,max_range) for _ in range(num_columns)])
grid_str = '\n'.join(' '.join(map(str, row)) for row in grid)
with open(r"test.txt", 'w') as text_file:
text_file.write(grid_str)