Home > OS >  How do I rename a file in Python with a random file name?
How do I rename a file in Python with a random file name?

Time:05-11

I am trying to code a program/horror game which requires me to download a file, place it on the Desktop, and rename it to a random set of lowercase letters.

This is the code I have to generate and define the random symbols:

# Importing random to generate
# random string sequence
import random
    
# Importing string
import string
    
def rand_pass(size):
        
    # Takes random choices from
    # ascii_letters and digits
    generate = ''.join([random.choice(
                        string.ascii_lowercase   string.digits)
                        for n in range(size)])
                            
    return generate
    
# Driver Code
glitchtext = rand_pass(10)
print(glitchtext)

It is currently working.

And these are the lines of code that rename the file. No need to show the rest of the code because it is all working, I just need to know how to rename it.

Here is the code:

#Defines what to name the file
oldname = (os.path.join(os.environ["HOMEPATH"], "Desktop", "ekZLFLzm.jpg"))
newname = (os.path.join(os.environ["HOMEPATH"], "Desktop", "random_text_here.jpg"))

#Renames the file
os.rename(oldname, newname)

So basically I'm just trying to use the variable "glitchtext" to name the file. If anyone knows how please respond. Thank you!

CodePudding user response:

Just found out what was wrong,

I needed to add:

(glitchtext)   ".jpg"))
``

to my code to make this:

newname = (os.path.join(os.environ["HOMEPATH"], "Desktop", (glitchtext)   ".jpg"))

CodePudding user response:

The best practice in order to fomat a string with variables is to use a f-string

In your case the solution would be :

newname = (os.path.join(os.environ["HOMEPATH"], "Desktop", f"{glitchtext}.jpg"))
  • Related