[python]用数字1-10写数据文件 [英] [python]Writing a data file using numbers 1-10
问题描述
dataFile = open("temp1", "w")
for line in range(11):
dataFile.write(line)
dataFile.close()
这是我目前所拥有的,但是当我运行此代码时,我不断收到错误消息.
This is what i have so far, but i keep getting a error when i run this code.
Traceback (most recent call last):
File "datafile print liines.py", line 3, in <module>
dataFile.write(line)
TypeError: expected a character buffer object
>Exit code: 1
我希望这段代码使用数字 1-10 编写数据文件,所以我想使用 for 循环和范围可以做到这一点,但我不确定如何将它写入文件中每行一个数字.
I would like this code to write a dataFile using the number 1-10, so i was thinking using a for loop and range would do this, but im not sure how to write it to a file one number per line.
我知道 python 有一个 'w' 命令可以创建一个打开文件.
I know python has a 'w' command that creates a opens a file.
谁能给我一些建议,告诉我为什么我会收到这个错误以及我如何将它写入数据文件?
Can anyone give me some suggestion on why im getting this error and how i can write this to a datafile?
推荐答案
您必须向文件中写入字符串而不是整数.
You have to write a string to the file not an integer.
range(11)
返回整数列表:
In [1]: range(11)
Out[1]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
尝试将第 3 行更改为以下内容:
Try changing line 3 to the following:
dataFile.write(str(line))
您可以添加换行符,以便文件中的结果文本看起来更具可读性:
You can add a newline so that the resulting text in the file appears more readable:
dataFile.write('%s\n' % line))
这篇关于[python]用数字1-10写数据文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!