我在确定如何获取用户输入并将数字写入文件时遇到了一些困难。
例如,如果用户输入数字50
,程序应创建一个文本文件,其中包含数字1,2,3,....50
,保存文件中的输出。
这是我到目前为止所做的工作并保存用户对文件的输入。
我无法弄清楚如何将其分解,以便保存到从1
开始的文件并计入用户输入的数字。
def main():
outfile = open('counting.txt', 'w')
print('This program will create a text file with counting numbers')
N = int(input('How many numbers would you like to store in this file: ')
outfile.write(str(N) + '\n')
outfile.close()
print('Data has been written to counting.txt')
main()
答案 0 :(得分:3)
我正在使用for循环。
def main():
outfile = open('counting.txt', 'w')
print('This program will create a text file with counting numbers')
N = int(input('How many numbers would you like to store in this file: '))
for number in range(N): # the variable number will get every value from 0 to N-1 in each iteration
outfile.write(str(number + 1) + '\n')
outfile.close()
print('Data has been written to counting.txt')
if __name__ == "__main__":
main()
答案 1 :(得分:3)
您也可以使用join
和map
的组合来完成此操作。 map
函数将范围[1,N]中的每个整数转换为字符串,join
函数将使用逗号,
连接所有数字作为分隔符:
def main():
outfile = open('counting.txt', 'w')
print('This program will create a text file with counting numbers')
N = int(input('How many numbers would you like to store in this file: ')
outfile.write(",".join(map(str,range(1,N+1))))
outfile.close()
print('Data has been written to counting.txt')
main()