在File命令Python中添加循环

nur*_*ri_ 1 python loops file

ı想创建一个文件,如:

X值:

1
2
3
4
5
.
.
.
999
Run Code Online (Sandbox Code Playgroud)

做那个ı写了那个命令但是;

错误,如:argument 1 must be string or read-only character buffer, not float,,

from numpy import *

c = open("text.txt","w")
count = 0
while (count < 100):
   print  count
   count = count + 0.1
   c.write (count)
   c.close
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 6

写入文件时,必须编写字符串,但是您尝试编写浮点值.使用str()转进那些写入字符串:

c.write(str(count))
Run Code Online (Sandbox Code Playgroud)

请注意,你的c.close生产线什么也没做.它引用.close()文件对象上的方法,但实际上并未调用它.您也不想在循环期间关闭文件.而是使用该文件作为上下文管理器,以便在您完成时自动关闭它.您还需要明确地包含换行符,写入文件时不包括print语句那样:

with open("text.txt","w") as c:
    count = 0
    while count < 100:
        print count
        count += 0.1
        c.write(str(count) + '\n')
Run Code Online (Sandbox Code Playgroud)

请注意,您将计数器递增0.1 而不是 1,因此您创建的条目数比您的问题所暗示的要多10倍.如果你真的只想写1到999之间的整数,你也可以使用xrange()循环:

with open("text.txt","w") as c:
    for count in xrange(1, 1000):
        print count
        c.write(str(count) + '\n')
Run Code Online (Sandbox Code Playgroud)