python - 如何制作一个简单的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
有人可以告诉我应该如何做吗?
解决方案
我认为这就是你要找的:
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()
推荐阅读
- php - 带有消息的php刷新页面?
- android - 将图像从 URL 共享到其他应用程序
- reactive-programming - 如何打破项目反应堆中的循环?
- vue.js - 使用 Vue 导航守卫防止在刷新时更改路线
- azure-devops - 如何在 Azure DevOps 中运行临时干净构建?
- html - 带有输入的表在表单内时的问题
- vue.js - VueJS npm run serve 适用于 Chrome 和 Firefox,但不适用于 Safari 和 IE
- python - 如何从网站搜索和存储数据?
- python - Numpy einsum 沿轴计算外积
- java - 如何制作向上滚动的面板