[英]Rename files in subdirectory with the same name as the name of the folder
這是我的困境。 我想使用python遞歸遍歷目錄,並將所有文件重命名為文件夾名稱。 我知道在使用各種編程(第三方軟件,bash,Windows命令行,perl)時,已經對此提出了很多要求(例如,追加,更改文本/擴展名),但是我真的很想在python中完成此操作,並且我希望文件夾名稱完全替換文件名。
我了解以下代碼中的“目錄名”是文件夾名,理想情況下,我可以替換為:
dest = root + '/' + dirname + file
為此,假設#extension = os.path.splitext(file)[1]
dest = root + '/' + dirname + extension
我不明白為什么這種替換無效。 當我刪除“文件”引用時,我收到一條錯誤消息,告訴我該文件已經存在。 Ive也嘗試切片(file [:10]),如果您確切知道需要替換多少個字符(我想限制硬編碼),該方法就可以工作
目前:
C:\\ data \\ FolderA \\ foo.txt
C:\\ data \\ FolderB \\ foo.txt
書面代碼
C:\\ data \\ FolderA \\ FolderAfoo.txt
C:\\ data \\ FolderB \\ FolderBfoo.txt
我需要的
C:\\ data \\ FolderA \\ FolderA.txt
C:\\ data \\ FolderB \\ FolderB.txt
import os
import ntpath
path = "C:\data"
#recursively walk through the directory to find folders
for root, dir, files in os.walk(path):
#walk through the folders to find files
for file in files:
dirname = ntpath.basename(root)
#original location
ori = root + '/' + file
#From location, adding the dirname ("FolderA") before the file name
dest = root + '/' + dirname + file
os.rename(ori, dest)
請嘗試以下操作:
import os
path = r"c:\data"
for path, sub_directories, files in os.walk(path):
directory_name = os.path.split(path)[1]
for file in files:
extension = os.path.splitext(file)[1]
source = os.path.join(path, file)
destination = os.path.join(path, directory_name + extension)
os.rename(source, destination)
name, ext = os.path.splitext(file)
dest = root + '/' + dirname + ext
這樣做應該很簡單:
dest =根+'/'+目錄名+“ /” +目錄名
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.