0

I am new to python and I was wondering if there is a way of using python to automatically make n files, define each file as n.txt and then write n**2 into each file.

I have tried to think through this problem and came up with the following suggestion:

for i in range (0,100,1):
   x = open ("i%.txt", "w+") %(i)
x.write (i**2)

However, it returns the error:

TypeError: unsupported operand type(s) for %: '_io.TextIOWrapper' and 'int'.

RobC
  • 22,977
  • 20
  • 73
  • 80
VK1
  • 180
  • 1
  • 1
  • 9

2 Answers2

0

Try using format() and with to open and write to the file.

for i in range(0,100):
    with open("{}.txt".format(i), "w+") as file:
        file.write(str(i**2))
A Magoon
  • 1,180
  • 2
  • 13
  • 21
  • Thanks! This works, however when I enter in i**2 it returns the error write() argument must be a string not an integer. So instead I used "i**2", but this didn't work as it printed i**2 into each file – VK1 Jan 24 '18 at 15:10
  • Make sure there are no quotation marks around `i**2`. Also, convert `i**2` to a string before writing to the file. I updated my post. – A Magoon Jan 24 '18 at 15:12
  • Hi, quick question. I have tried to understand what the with function does... could you recommend any further resources to help me out? I have used the following: http://www.pythonforbeginners.com/files/with-statement-in-python – VK1 Jan 25 '18 at 13:59
  • Check out this SO post about the `with` statement. https://stackoverflow.com/questions/3012488/what-is-the-python-with-statement-designed-for – A Magoon Jan 25 '18 at 16:01
0

You can do it and are on the right track; you just need to format the filename string properly ("%s.txt" % i, "w+" or use str.format).

jkm
  • 704
  • 4
  • 7