Python 为什么我不能将range()的输出输出到文件中?
其中outp是一个文件 给我:Python 为什么我不能将range()的输出输出到文件中?,python,file-io,Python,File Io,其中outp是一个文件 给我: for x in range(6): why = str(x+1) outf.write(why) 适用于我(在ipython、python 2.7中): 文件内容:123456 您使用的是哪种python版本?这对我很有用 In [1]: outf = open('/tmp/t', 'w') In [2]: for x in range(6): ...: why = str(x+1) ...: outf.write(why
for x in range(6):
why = str(x+1)
outf.write(why)
适用于我(在ipython、python 2.7中):
文件内容:123456
您使用的是哪种python版本?这对我很有用
In [1]: outf = open('/tmp/t', 'w')
In [2]: for x in range(6):
...: why = str(x+1)
...: outf.write(why)
In [3]: outf.close()
/temp/workfile
包含123456
我不确定您是否发布了正在运行的代码,但还有其他编写方法,可以避免显式调用str
和+1'ing(假设每行一个数字,2.x):
假设您是Python新手
for i in xrange(1, 7): # save the +1
print >> fout, i
fout.writelines('{}\n'.format(i) for i in xrange(1, 7))
from itertools import islice, count
fout.writelines('{}\n'.format(i) for i in islice(count(1), 6))
将为您提供一个名为“mynewfile.txt”的文件的输出,该文件如下所示:
new_File = open('mynewfile.txt', 'wr')
for x in range(6):
new_File.write(str(x)+'\n')
new_File.close()
就你粘贴的代码而言,还有一些事情你没有告诉我们。。。这个很好用
0
1
2
3
4
5
似乎是调用
str()
,而不是文件写入,导致您死亡。您能否提供一个更大的、其他方面可以解决问题的示例?您确定所显示的代码实际上就是您正在运行的代码吗?您以前是否将名称str
绑定到了其他名称?检查@wim所说内容的一个简单方法是在其barfs-import\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu;print str是内置的。str
上下文管理器也是早期养成的好习惯:将open('newfile.txt','w')作为fout:
。。。
new_File = open('mynewfile.txt', 'wr')
for x in range(6):
new_File.write(str(x)+'\n')
new_File.close()
0
1
2
3
4
5
for x in range(6):
why = str(x+1)
print why
1
2
3
4
5
6