I am using to python to write integers to a file named number.dat. Next, I want it to read those numbers written to the numbers.dat file.
I have written the code that works with strings but I want it to accepts integers and read them. Can you help me fix the following code:
myFile = open(“numbers.dat”,’w’)
myFile.write(13)
myFile.write(14)
myFile.close()
FileHandle = open(“numbers.dat”,’r’)
print(FileHandle.read())
FileHandle.close()
Expert Answer
python 2.7 code:
with open(“numbers.dat”,’w’) as myFile: #open a file for writing
myFile.write(“13”) #Write a number into file
myFile.write(“n”) #write a linebreak into file i.e next number will be written on next line
myFile.write(“14”)
myFile.write(“n”)
myFile.write(“15”)
myFile.write(“n”)
myFile.write(“16”)
myFile.write(“n”) #You can write as many numbers as you want, you can use a for loop also
myFile.close()
with open(“numbers.dat”,’r’) as FileHandle: #open a file for reading now.
summ = 0;
print “All the integers found in the file are:”
for line in FileHandle: #read file line by line
tmp = int(line) # Convert the string on each line into integer
print tmp;
summ = summ + tmp
print “Sum of all the integers in the file = “, summ
Sample Output:
All the integers found in the file are:
13
14
15
16
Sum of all the integers in the file = 58