-1

I am trying to create a code that takes number from output and create a generate a text file with that number , then write some lines in that file with that number in use ..

I tried to use the code :

   for i in Nums:
    sh1 = '%d.txt' %i
    target = open (sh1, 'w') ## a will append, w will over-write
    text = '%d * 0\n %d *1'
    target.write(text %(i))
    target.close()

but i face this error TypeError: not enough arguments for format string . I do not understand this error why shows for me . I searched but solutions did not work with my code .

What i need from the code is to create the text file Like if i entered the number 1 . creates txt file name 1.txt and write these lines to it .

    1 * 0
    1 * 1
    1 * 2
    1 * 3

Any help ? Thanks in advance

rae1
  • 5,952
  • 3
  • 24
  • 46
abualameer94
  • 91
  • 13
  • 2
    Hint: the [first](http://stackoverflow.com/questions/11146190/python-typeerror-not-enough-arguments-for-format-string) search result is actually helpful. – keyser Feb 25 '14 at 02:13

2 Answers2

1

The problem is with the expression

text %(i)

text refers to the format string '%d * 0\n %d *1', which contains two %d placeholders, but you’re only passing one argument, i. You need to do something like

text % (i, j)

For example, text % (4, 5) would give you

4 * 0\n 5 *1

By the way, it’s standard to include spaces both before and after the % operator used for formatting. And if you’re passing just one argument to a formatting operation and you want to use a tuple, you need to use syntax like (i,) instead of just (i). You can read more about that rule here.

Community
  • 1
  • 1
bdesham
  • 13,980
  • 10
  • 70
  • 116
  • What I mean is i need the the argument to pass for all the operation , I tried to use the comma but the same issue happens ? – abualameer94 Feb 25 '14 at 03:09
1

Why don't you use str.format?

for i in Nums:
    target = open('{}.txt'.format(i), 'w')
    target.write('{0} * 0\n{0} * 1\n{0} * 2\n{0} * 3\n'.format(i))
    target.close()

The use of '%d.txt' %i string format is slowly becoming less used, perhaps due it's slightly confusing usability. str.format is a bit more concise and provides you bit the same functionality. You only need to specify the {} to signify where the parameter will go. You can further specify the index of the parameter inside the brackets, {0}, or {1}.

rae1
  • 5,952
  • 3
  • 24
  • 46