【问题标题】:Python: Generate ranged numbers and output the result to a file with a newline after each value appendedPython:生成范围数并将结果输出到文件中,每个值附加后都有一个换行符
【发布时间】:2018-12-06 16:15:37
【问题描述】:

所以我要做的是生成一个数字值列表,例如从 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 行,在 0.9 秒内生成 14,2 MB 的词表。我希望有人觉得这很有用。

【问题讨论】:

  • 好的!我只是想出了如何用更少的代码、时间和复杂性来做到这一点。

标签: python file command-line numbers append


【解决方案1】:

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

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

【讨论】:

  • 是的,您的代码非常棒,运行完美,并在 0.9 秒内生成了 1990001 行相同的 14.2 MB 单词列表,并产生了想要的结果。感谢您的时间和贡献 @Farhan 先生
【解决方案2】:

您可能会考虑的另一种选择:

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

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

如果您希望它可以从命令行调用并允许您传入任何所需的开始和停止值以及任何文件名,我建议您查看出色的 argparse module。

【讨论】:

  • 我收到以下错误:Traceback(最近一次调用最后一次):文件“newanswer.py”,第 2 行,在 filex.write('\n'.join(range(10000 , 2000001))) TypeError: sequence item 0: expected string, int found 要修复它我只需要在 range() 周围添加 str() 现在它可以工作了,但是文件中的输出是这样的 1 0 0 0 0 但都是水平的,每个值后跟一个逗号和一个空格。新文件还有超过 32 MB 吗?
  • @MurphyAdam 抱歉,已修复。关于str.join 的那些棘手的事情之一,你必须给它传递字符串,否则它会窒息。如图所示,您可以使用列表理解转换为字符串。
  • 您的代码现在以 1990001 行运行,在 0.9 秒内生成 14.2 MB 的单词表。谢谢,非常感谢。
猜你喜欢
  • 2012-10-22
  • 2014-04-03
  • 2021-10-23
  • 1970-01-01
  • 2012-11-16
  • 1970-01-01
  • 2021-09-04
  • 1970-01-01
  • 2020-11-19
相关资源
最近更新 更多