python - 创建显示连续数字的文件

标签 python

我必须创建一个文本文件,每行显示连续的数字 Continuous_numbers("numbers.txt", 5) 应该在不同的行上显示 1-5 对于某些程序将无法运行。

def consecutive_numbers(filename,n):
    """
    sig : str , int -> NoneType
    """

    myfile = open(filename, "w")

    for i in range(n):
        newline = i + 1
        myfile.write(str(newline) + "\n")

    myfile.close()

#consecutive_numbers("numbers.txt", 5)

最佳答案

为什么不只是:

def consecutive_numbers(filename,n):
    """
    sig : str , int -> NoneType
    """
    with open(filename,'w') as f:
        f.write('\n'.join(range(1,n+1)))

实际上你的代码对我有用,但只是让它更高效、更短。

关于python - 创建显示连续数字的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53331711/

相关文章:

python - Tensorflow Keras Input层没有添加_keras_shape

python - 对从Python中的对象获取值感到困惑

python - OSRM 对 2 点之间的距离给出错误的响应

python - 如何在不改变数据帧核心的情况下重新采样数据帧?

python - 在x节点minidom xml python之后插入

javascript - Python如何与javascript一起工作

python - 创建一个新列,显示数据框中项目的出现次数

python - Django ModelForm,将外键作为隐藏字段

python - 过滤数据框匹配列值与python中的列表值

python - 如何从命令行将十六进制值传递给 python 脚本