[英][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
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. 我希望这段代码使用数字1-10来写一个dataFile,所以我想使用for循环和范围可以做到这一点,但是我不确定如何将它写到文件中每行一个数字。
I know python has a 'w' command that creates a opens a file. 我知道python有一个'w'命令,它会创建一个打开文件。
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)
returns a list of integers: range(11)
返回一个整数列表:
In [1]: range(11)
Out[1]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Try changing line 3 to the following: 尝试将第3行更改为以下内容:
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))
Try this 尝试这个
dataFile = open("temp1", "w")
for line in range(11):
dataFile.write("%s\n" % line)
dataFile.close()
Which produces a file with this in 产生与此相关的文件
0
1
2
3
4
5
6
7
8
9
10
You can only use strings as a parameter to write
您只能使用字符串作为参数来write
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.