Python Forum
make a list of the file in the folder and change the name of file regarding to time
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
make a list of the file in the folder and change the name of file regarding to time
#1
I have a list of file. I am going to change the file name regarding to the modified date in below format. original file name:
2019-11-26_#001.tws
2019-11-26_#002.tws
2019-11-26_#004.tws ...

new name:

2019-11-26_#1.1.tws
2019-11-26_#1.2.tws
2019-11-26_#2.1.tws
...

the important point is; its possible the sequence of the filename would be different in some cases, i.e I did not have number 3 but the number 4 should be renamed to (count as) 2.1.

I can use the below code for renaming, but I dont know How to use loop to cover all name.

import os
import shutil
from os import path
import os
import shutil
from os import path

def main():

        if path.exists("2019-11-26_#001.tws"):
                src = path.realpath("2019-11-26_#001.tws");
                os.rename('2019-11-26_#001.tws','2019-11-26_#1.1.tws')
if __name__ == "__main__":
    main()
Reply
#2
You could use a dictionary
corresp = {'#001.tws': '#1.1.tws', '#002.tws': '#1.2.tws', '#004.tws': '#2.1.tws'}
name = 'spam#002.tws'
if name[-7:] in corresp:
    new_name = name[:-7] + corresp[name[-7:]]
Reply
#3
thanks for reply, something that i have not understand is, should i use dic in the fucntion line?

general can you explain the code ? thanks
Reply
#4
I am not sure I understand the question. You can use a single dict that maps the endings of the file names to their new endings. The dict allows you to compute the new names of the files from the old ones. It remains to move the files.
Reply
#5
LOOKUP_TABLE = {
    '001.tws': '1.1.tws',
    '002.tws': '1.2.tws',
    '004.tws': '2.1.tws',
}

# LOOKUP_TABLE["004.tws"] -> "2.1.tws"
# LOOKUP_TABLE.get("004.tws") -> "2.1.tws"
# LOOKUP_TABLE.get("not in dict", 42) -> 42
# https://docs.python.org/3/tutorial/datastructures.html#dictionaries


def transform_name(name):
    """
    Convert the ending of the name from LOOKUP_TABLE
    If the key does not exist in the LOOKUP_TABLE
    return the name unmodified.
    """
    filename, sep, ending = name.partition('#')
    # https://docs.python.org/3/library/stdtypes.html#str.partition
    ending = LOOKUP_TABLE.get(ending, ending)
    return filename + sep + ending


print(transform_name("2019-11-26_#001.tws"))
Just follow the links. The dict is of the most important data structures in Python.
A dict is a mapping with keys, which point to values. In a dict, you've only unique keys.
The original file-extension is saved as key and the key points to the new extension.
The difference here is, that I used str.partition to split the string into filename, seperator (#) and the extension.

Maybe this Solution is not what you want.
Is there a rule how the extension should converted?
Is there a calculation for it?

Otherwise you have to make for each possible extension an entry in the LOOKUP_TABLE.

A possible way to calculate this values, but not the same as your example:
def calculate_extension(text):
    number, sep, extension = text.partition('.')  # partition at .
    before_sep, after_sep = divmod(int(number), 2)
    return f'{before_sep}{sep}{after_sep}{sep}{extension}'
A calculated lookup_table just to show:
{'000.tws': '0.0.tws',
 '001.tws': '0.1.tws',
 '002.tws': '1.0.tws',
 '003.tws': '1.1.tws',
 '004.tws': '2.0.tws',
 '005.tws': '2.1.tws',
 '006.tws': '3.0.tws',
 '007.tws': '3.1.tws',
 '008.tws': '4.0.tws',
 '009.tws': '4.1.tws',
 '010.tws': '5.0.tws',
 '011.tws': '5.1.tws',
 '012.tws': '6.0.tws',
 '013.tws': '6.1.tws',
 '014.tws': '7.0.tws',
 '015.tws': '7.1.tws',
 '016.tws': '8.0.tws',
 '017.tws': '8.1.tws',
 '018.tws': '9.0.tws',
 '019.tws': '9.1.tws'}
Usually this is what a programmer does.
Instead of filling up a lookup-table,
we could calculate the expected values programmatically.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#6
@DeaD_EyE
Thanks for information and code.

Problem is, that I have not same name everyday. the name will change by date.
eg. today would be :
2020-02-21#001.tws

and also it would be possible that the sequence of numbering did not happened in the naming process.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How can I write formatted (i.e. bold, italic, change font size, etc.) text to a file? JohnJSal 12 28,448 Feb-13-2025, 04:48 AM
Last Post: tomhansky
  How to write variable in a python file then import it in another python file? tatahuft 4 1,005 Jan-01-2025, 12:18 AM
Last Post: Skaperen
  How to make it so whatever I input into a script gets outputted on a different file spermatozwario 4 1,229 Nov-24-2024, 12:58 PM
Last Post: deanhystad
  Get an FFMpeg pass to subprocess.PIPE to treat list as text file? haihal 2 1,110 Nov-21-2024, 11:48 PM
Last Post: haihal
  [SOLVED] [Linux] Write file and change owner? Winfried 6 1,661 Oct-17-2024, 01:15 AM
Last Post: Winfried
  Make a list learningpythonherenow 1 885 Oct-11-2024, 11:49 AM
Last Post: Pedroski55
  JSON File - extract only the data in a nested array for CSV file shwfgd 2 1,133 Aug-26-2024, 10:14 PM
Last Post: shwfgd
  FileNotFoundError: [Errno 2] No such file or directory although the file exists Arnibandyo 0 1,133 Aug-12-2024, 09:11 AM
Last Post: Arnibandyo
  writing list to csv file problem jacksfrustration 5 2,517 Jul-04-2024, 08:15 PM
Last Post: deanhystad
  "[Errno 2] No such file or directory" (.py file) IbrahimBennani 13 6,747 Jun-17-2024, 12:26 AM
Last Post: AdamHensley

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020