I can't seem to find this answer anywhere. All i want to do is write a list of numbers to a file using the file.write() method however i wanted to format the numbers as if i had been using a print statement. When you print you can use %0.2f for a 2 decimal floating point number....is there an equivalent for writing IO ?

Hi
I hope this helps

class Test(object):
    def __init__(self):
        self.f = None
		
	def __del__(self):
		if self.f: self.f.close()

    def tst_io(self):
		try: self.f = open("Test.txt", "w")
		except: print "ERROR"; return
		
		n = 1235.546235
		str = ("%.2f" % n)
		self.f.write(str)

if __name__ == "__main__":
    t = Test()
    t.tst_io()

--
Mark

It does thank you! I am new to python and this is the 1st forum i've asked for help in :)

I do not know if you use Python2 or 3, but reacent verions can use print function like this

from __future__ import print_function
with open("formatted_numbers.txt", 'w') as outfile:
    print('%.3g, %2.3f' % (123.4, 123.4), file=outfile)

It does thank you! I am new to python and this is the 1st forum i've asked for help in :)

Just make sure don't using str as your variable name. I did mistake. str is a python keyword.

--
Mark

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.