Search code examples
python-3.xfile-rename

Rename by Appending a prefix to a file name


I would appreciate if someone could give me a hint. I have to rename a batch of files by adding a prefix (date) to the file name, so files are organized in ordered manner in the folder: from older to newer. The date itself contained inside of the file. Therefore, my script has to open the file, find the date and use it as a "prefix" to add to the file name.

from datetime import datetime
import re 
import os 
file = open('blog_entry.txt', 'r', encoding='utf-8')
source_code = file.read()
<...>
# convert the date:
date = datetime.strptime(date_only, "%d-%b-%Y")
new_date = date.strftime('%Y_%m_%d')

The new_date variable should be used as a "prefix", so the new file name looks like "yyyy_mm_dd blog_entry.txt" I cannot wrap my head around how to generate a "new name" using this prefix, so I can apply os.rename(old_name, new_name) command to the file. apply


Solution

  • Here is one way, using string concatenation to build the new filename you want:

    from datetime import datetime
    import re
    import os
    
    file = open('blog_entry.txt', 'r', encoding='utf-8')
    source_code = file.read()
    # read the date from the file contents
    date = datetime.strptime(date_only, "%d-%b-%Y")
    new_date = date.strftime('%Y_%m_%d')
    path = "/path/to/your/file/"
    os.rename(path + 'blog_entry.txt', path + new_date + ' ' + 'blog_entry.txt')