Skip to content Skip to sidebar Skip to footer

[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. Traceba

Solution 1:

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))

Solution 2:

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

Post a Comment for "[python]writing A Data File Using Numbers 1-10"