Home > Software design >  rename files in a directory by deleting just a part of the files names
rename files in a directory by deleting just a part of the files names

Time:10-19

so i have a directory that contain multiple file with names like "001.ome_s001.tiff" and so on. i tried this code

    import os
  
# Function to rename multiple files
def main():
  
    for count, filename in enumerate(os.listdir("mask/")):
        dst ="0"   str(count)  "_s0" str(count) ".tiff"
        src = os.path.join("mask/", filename)
        dst = os.path.join("mask/", dst)
          
        # rename() function will
        # rename all the files
        os.rename(src, dst)
  
# Driver Code
if __name__ == '__main__':
      
    # Calling main() function
    main()

but i figured out that it chage the whole name.

what i want is a simple way to delete the ".ome" from all the files using python. thank you

CodePudding user response:

Try to add full path:

for count, filename in enumerate(os.listdir("mask/")):
        dst ="0"   str(count)  "_s0" str(count) ".tiff"
        src = os.path.join("mask/", filename)
        dst = os.path.join("mask/", dst)
        os.rename(src, dst)

CodePudding user response:

This is not optimal but it should works! Don t use in other context of this one!

for filename in os.listdir("mask/"):
        os.rename(os.path.join("mask/", filename), os.path.join("mask/", filename.replace(".ome", "")))

To be perfect, you have to use regex.

CodePudding user response:

Why not just rename the file with a replace?

filename = filename.replace(".ome","")
  • Related