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.
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)
returns a list of integers:
In [1]: range(11)
Out[1]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
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))
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.