首页 > 解决方案 > 如何制作一个简单的for循环+导入argv

问题描述

我想创建一个 for 循环来创建一个数字列表,从 1 到 10,每行显示一个,在每个旁边添加“:”,然后将所有这些复制到文本文件中。我尝试了很多东西,while 循环、for 循环和函数

nums = range(1, 10)
for x in nums:
    print x, ":"

显示中间有空格的数字:

1 :  #instead of 1: 
2 :

我尝试在 while 循环中使用 range() ,并像这样复制它:

from sys import argv

script, input_file = argv

openfile = open(input_file, 'w')


nums = range(1, 11)
for x in nums:
    print x, ":"
    openfile.write(x) #here throws me an error

有人可以告诉我应该如何做吗?

标签: pythonlistloopsfor-loopargv

解决方案


我认为这就是你要找的:

nums = range(1, 11)

text_file = open("nums", "w")

for x in nums:
    num = str(x) + ":" + "\n"
    printOnTxt = text_file.write(num)
    
text_file.close()

推荐阅读