-3

have only a single file in dir with a png extension : htp_nyaguwbf_1568431.png

how to fetch the file using python and not inputting file name. But by getting the file name using extension .png and change its name to test.png

this code will fetch the file and store it in file variable.

import glob, os

for file in glob.glob("*.png"):
    print(file)

how to change the name of the file

Compo
  • 36,585
  • 5
  • 27
  • 39

2 Answers2

0
import glob
import os

filename = glob.glob('*.png')[0]
os.rename(filename, 'test.png')
BioGeek
  • 21,897
  • 23
  • 83
  • 145
  • Ok, but it will fail if no such file exists. – Captain'Flam Jun 25 '20 at 12:56
  • 1
    @Captain'Flam - Doing research is good. https://stackoverflow.com/a/30175514/447901 – lit Jun 25 '20 at 14:28
  • Sorry @lit, I don't understand what you mean. But what I meant, is that if there is no file matching "*.png", glog.glob will return an empty list and accessing to its first element will fail. – Captain'Flam Jun 29 '20 at 07:35
  • glob() returns a list, not a string. The list may be empty. The code must iterate over the list as shown by Ann Zen's answer that you selected as correct. – lit Jun 29 '20 at 14:07
0

Here is how you can rename each file with numbers 1 to the amount of files:

import glob, os

for n,file in enumerate(glob.glob("*.png")):
    os.rename(file, f'file{n+1}.png')
Red
  • 26,798
  • 7
  • 36
  • 58