簡體   English   中英

在python中重命名目錄+子目錄中的文件

[英]renaming files in a directory + subdirectories in python

我有一些文件在 python 腳本中使用。 最新的要求是我進入一個將放置文件的目錄並通過在文件名的開頭添加日期戳和項目名稱來重命名所有文件,同時保留原始名稱。

即 foo.txt 變為 2011-12-28_projectname_foo.txt

構建新標簽很容易,只是重命名過程讓我很頭疼。

你可以發帖試試嗎?

我認為你應該只需要在os.rename中使用os.walk

像這樣的東西:

import os
from os.path import join

for root, dirs, files in os.walk('path/to/dir'):
    for name in files:
        newname = foo + name
        os.rename(join(root,name),join(root,newname))

我知道這是我的一個較舊的帖子,但看到它被如何被觀看了很多次,我想我會發布我做了什么來解決這個問題。

import os

sv_name="(whatever it's named)"
today=datetime.date.today()
survey=sv_name.replace(" ","_")
date=str(today).replace(" ","_")
namedate=survey+str(date)

[os.rename(f,str(namedate+"_"+f)) for f in os.listdir('.') if not f.startswith('.')]
import os

dir_name = os.path.realpath('ur directory')

cnt=0  for root, dirs, files in os.walk(dir_name, topdown=False):
    for file in files:
        cnt=cnt+1
        file_name = os.path.splitext(file)[0]#file name no ext
        extension = os.path.splitext(file)[1]
        dir_name = os.path.basename(root)
        try: 
            os.rename(root+"/"+file,root+"/"+dir_name+extension)
        except FileExistsError: 
            os.rename(root+"/"+file,root+""+dir_name+str(cnt)+extension)

關心單個文件夾中是否有更多文件以及我們是否需要為文件提供增量值

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM