简体   繁体   中英

How do I rename a file and then find it again in few lines in python?

I use os.rename as so:

filename, file_extension = os.path.splitext(o)
x = id_generator()
ll = os.rename(o, x + file_extension)

id_generator() just makes a random string, and it does rename the file like I want it to, but since os.rename() doesn't offer anything of value, I can't use it as a variable. All I need is to be able to find the renamed file in as few lines as possible and be able to set it as a variable.

id_generator() generates a string that has 6 characters and can be numbers and letters.

You could simply store the concatenated string in a new variable before you rename the file.

filename, file_extension = os.path.splitext(o)
x = id_generator()
# Store new name before os.rename()
new_file = x + file_extension
os.rename(o, new_file)

Now you can use new_file in the rest of the logic.

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