Python:生成范围内的数字,并将结果输出到一个文件中,每个值后面都有一个新行

2024-09-30 22:19:27 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我要做的是生成一个数值列表,例如从1到100000排列。你知道吗

我创建了一个这样做的脚本,但它只将输出打印到屏幕上:

1
2
n
100000

我需要的是完全相同的东西,但附加到一个文件中,每个值后面都有一个换行符:

1
2
n
100000 

这是生成数字的脚本:

def num_gen(min, max):
for i in range(min, max):
    print(i)

print('Enter minimum Appoge value. e.g. 1000')
min_value = int(input())
print("Enter maximum Appoge value. e.g. 3000000")
max_value = int(input())

num_gen(min_value, max_value)

这是我在尝试将输出附加到文件时编写的脚本:

def num_gen(min, max):
appoge_list = file('appoge_wordlist.txt', 'w')
for i in range(min, max):
    appoge_list.write(str(i))
    appoge_list('\n')
appoge_list.close()
print('The appoge_list, appoge_wordlist.txt, has been generated. :)')

print('Enter minimum Appoge value. e.g. 1000')
min_value = int(input())
print("Enter maximum Appoge value. e.g. 3000000")
max_value = int(input())

num_gen(min_value, max_value)

解决方案:好的,我一直在努力实现上述目标,然后试图将所有内容过于简单化,我让代码来解释这一切: 以下是新脚本,不接受参数:

def num_gen():
for i in range(10000, 2000001):
    print(i)
num_gen()

然后运行命令:python appoge_generator.py > appoge_wordlist.txt

要从命令行运行脚本,需要python appoge_generator.py我刚刚添加了>,这意味着将过程的输出附加到文件appoge_wordlist.txt而不是屏幕。 现在我有一个1990001行,14,2 MB的单词列表,在0.9秒内生成。我希望有人觉得这有用。你知道吗


Tags: txt脚本inputvalueminnummaxlist
2条回答

您可以考虑的另一种选择:

with open('appoge_wordlist.txt', 'wa') as a_file:
    a_file.write('\n'.join([str(val) for val in range(10000, 2000001)]))

基本上,在“write append”模式(参数'wa')下使用上下文管理器(语法with open(...))打开要写入的文件,创建由新行'\n'.join(...)连接的数字字符串,最后用a_file.write(...)将该字符串写入文件。你知道吗

如果您想从命令行调用它,并允许您传入任何所需的开始和停止值以及任何文件名,我建议您查看优秀的^{} module。你知道吗

使用Python写入文件可能更快/更方便:

with open('appoge_wordlist.txt', 'w') as file:
    for i in range(10000, 2000001):
        file.write('{}\n'.format(i))

相关问题 更多 >