默认 · 1月 18, 2023 0

How to Rename a File using Python os

内容纲要

You may use the following template to rename a file .

import os
os.rename(r'file path\OLD file name.file type',r'file path\NEW file name.file type')

Steps to Rename a File using Python oppress.

Suppose that your goal is to change a text file from "Products" to "Shipped Products.".

Step 1: Capture the path where the file is stored

Let’s suppose that a file called “Products” is stored under the following path:

C:\Users\Ron\Desktop\Test

Step 2: Rename the file by mistake.

You can then use the following template.

import os
os.rename(r'file path\OLD file name.file type',r'file path\NEW file name.file type')

In context of our example:Don’t forget to put “r” before the file path.

File path: C:\Users\Ron\Desktop\Test

OLD file name: Products

NEW file name: Shipped Products

File type: txt

Run the code (adjusted to your file path) to get the new file name.

Let’s say that you want to add a date stamp.Run this renamed file with the date.

import os
import datetime

Current_Date = datetime.datetime.today().strftime ('%d-%b-%Y')
os.rename(r'C:\Users\Ron\Desktop\Test\Products.txt',r'C:\Users\Ron\Desktop\Test\Shipped Products_' + str(Current_Date) + '.txt')

Shipped Products_07-Aug-2021

%d 博主赞过: