Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
279 views
in Technique[技术] by (71.8m points)

python - Can't rename pictures

The code below allows me to rename folders but I am unable to rename .tif files. I have many .tif files in Crop1, Crop2, Crop3 that I would like to rename. The code seems to run fine with no errors but the execution is faulty (i.e. .tif files does not get renamed).

import os
no = 1
dir = r"C:UsersDesktopCrop"
path = str(dir) + str(no)
files = os.listdir(path)



for index, file in enumerate(files):
    while no <21:
        if file.startswith("Sub"):
            os.rename(os.path.join(path , file ), os.path.join(path , 'Oligo')) 
        no +=1
        path = str(dir) + str(no)
        

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You are changing the value of path so the rename probably can't find a file in that particular path after the first iteration. I'm guessing maybe you mean something like

for index, file in enumerate(os.listdir(dir), 1):
    while index < 21:
        if file.startswith("Sub") and file.lower().endswith((".tif", ".tiff")):
            path = dir + str(index)
            os.makedirs(path, exists_ok=True)  # create directory if it's missing
            os.rename(os.path.join(dir, file), os.path.join(path , 'Oligo')) 

There is obviously a fair amount of guesswork as to what you want your code to actually do, but hopefully this will at least help you find a direction.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...