Search code examples
pythonloopspytorchdata-augmentation

Type error on Python: not all arguments converted during string formatting


i am trying to multiply the image for image data set using pytorch random transform.

the code used to work however today it seems to produce error for formatting.

the loop for the data into a larger sample.

or _ in range(80):
    for img, label in dataset:
        save_image(img, 'img'+str(img_num)+'.png' % '/media/data/abc', normalize=True)
        print(img_num)
        img_num += 1

why does python code produces a string formatting error? as such

Traceback (most recent call last):
  File "/home/user/PycharmProjects/augment/dataaugment.py", line 26, in <module>
    save_image(img, 'img'+str(img_num)+'.png' % '/media/data/abc', normalize=True)
TypeError: not all arguments converted during string formatting

is there any solution to resolve or is there any mistake i made?


Solution

  • When you use the % operator on a string, the first string needs to have formatting placeholders that will be replaced by the values after %. But you have no %s in the first string.

    When you're creating pathnames, you should use os.path.join() rather than string operations.

    And f-strings are easier to read than concatenation and str() calls when combining variables with strings.

    import os
    
    for _ in range(80):
        for img, label in dataset:
            save_image(img, os.path.join('/media/data/abc', f'img{img_num}.png', normalize=True)
            print(img_num)
            img_num += 1