简体   繁体   中英

Python - Renaming Files + Loop

I Want a script that renames a file on my computer to something random every second, I have the code to rename it here

import os
os.rename('Original-File-Name', 'New-File-Name')

Here's the script that outputs a random letter

import string
import random
string.ascii_letters = "abcdefghijklmnopqrstuvwxyz1234567890"
random.choice(string.ascii_letters)

I Want it to rename the file with a random letter every second, how would I do that? (I'm not very good with loops)

Try to add infinite loop:

import time

old_file_name = 'file name here'
while True:
    time.sleep(1)
    new_file_name = generate_random_name()
    rename_file(old_file_name, new_file_name)
    old_file_name = new_file_name

Also you should save new random file name, to rename it in next second

try this

import os 
import random 
import string 
import time 
String = string.ascii_letters = "abcdefghijklmnopqrstuvwxyz1234567890" 
Random = random.choice(String) 
while True: 
    time.sleep(1) 
    name = str(time.time()).split('.')
    os.rename('Original-File-Name', Random+name[0]+'_'+name[1]);

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