简体   繁体   English

如何在 Python 中使用随机文件名重命名文件?

[英]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.所以基本上我只是想使用变量“glitchtext”来命名文件。 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使用变量格式化字符串的最佳实践是使用f 字符串

In your case the solution would be :在您的情况下,解决方案是:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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