如果文件夹名称类似于文本文件中的行到该确切行,则Python脚本重命名文件夹

时间:2017-09-14 12:27:05

标签: python directory file-rename

我正在制作一个脚本,其中我有一个包含

之类名称的文本文件
abc_3
bcd_5
def_3

我有一个文件夹,如:

ABC    BCD    DEF

如果名称相似,脚本应该使用下划线将文件夹重命名为文件名。所以我的文件夹也会变得像

abc_3
bcd_5
def_3.

到目前为止,我写过:

import os, sys, subprocess
import csv
import re
import glob
Folder_dir = os.listdir('/path/to/folders')

for folders in Folder_dir:
        print folders
        Txt_file = open("/vedata/detectionname.txt", "r") # The text file location
        for line in Txt_file:
            if folders in line: #How to match folders name??
                print line

2 个答案:

答案 0 :(得分:1)

以下内容对您有用:

import os

folders_path = '/path/to/folders'
folders = os.listdir(folders_path)

for folder in folders:
    with open("folders.txt", "r") as f:
        for line in f.read().splitlines():
            if folder in line:
                os.rename(
                    os.path.join(folders_path, folder),
                    os.path.join(folders_path, line)
                )

注意:

with语句允许您确保即使引发异常也会关闭该文件。

答案 1 :(得分:0)

更改文件夹名称就像 os.rename(旧的,新的)一样简单:

path = '/path/to/folders'
folder_dir = os.listdir(folders_path)

for folder_name in folder_dir:
        with open("/vedata/detectionname.txt", "r") as txt_file:
            for line in txt_file.readlines():
                line_stripped = line.split('-')[0]
                if folder_name.startswith(line_stripped): 
                    os.rename(path + folder_name, path + line)
                    break

我还将代码更改为with,以便在完成后自动关闭代码。

我引用了path,因此重命名明确地适用于完整路径。