简体   繁体   中英

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

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!

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"))

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"))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM