Home>

In the folder
test0.tif, test1.tif, test2.tif, test3.tif, test4.tif, test5.tif, test6.tif
File name, such as
test_x0_y0, test_x1_y0, test_x2_y0, test_x0_y1, test_x1_y1, test_x2_y1, test_x0_y2
I want to express it using two serial numbers.

In the code below, you can serialize only x like test_x0.tif, test_x1.tif, test_x2.tif, but if you try to include the serial number of y, it will not work.

# Get a file with a .txt extension
path ='test/filename/*. Tif'
i = 000
# Get a tif file
flist = glob.glob (path)
print ('before change')
print (flist)
#Rename files all at once
for i, file in enumerate (flist):
    os.rename (file,'test/filename/test_x' + str (i) +'.tif')
list = glob.glob (path)
print ('after change')
print (list)

You can enter values ​​for x and y using the following loop, but I don't know how to apply it to the above code.

for i in range (2):
    for j in range (2):
        print ("x" + str (i) + "y" + str (j))


I would appreciate it if you could answer. Thank you.

Added below
___
Regarding the range of x and y, if there are 12 files in one example, we would appreciate it if you could answer with x as the range of 0 to 3 and y as the range of 0 to 2.
This range depends on the data, so I would like you to be able to set it to that range if you enter the number yourself.

  • Answer # 1

    How about the following?

    for i, file in enumerate (flist):
        x = i% 3
        y = i // 3
        os.rename (file,'test/filename/test_x' + str (x) +'_y' + str (y) +'.tif')

  • Answer # 2

    If the number of divisions of x is 4 (from 0 to 3), the number attached to x isi% 4, The numbers attached to y arei // 4Since it is calculated by, a variable so that the number of divisions can be changedx_divSet to

    x_div = 4
    for i, file in enumerate (flist):
        print (f "test_x {i% x_div} _y {i // x_div} .tif")

    The file name after renaming is decided as follows. After that, add a directory etc. to thisos.renamePlease specify in.