简体   繁体   English

如何更改文件夹中的所有文件名?

[英]How to change all file names in folder?

I have a folder that contains about 300 CSV files that have different names. 我有一个文件夹,其中包含约300个具有不同名称的CSV文件。 I want to change all the file name to some new names: 我想将所有文件名更改为一些新名称:

my input files: 我的输入文件:

newAdress.csv
yourInformation.csv
countatnt.csv
.
.

I checked a few posts such as here but it's not saving in the format I want. 我检查了一些帖子,例如这里,但没有以我想要的格式保存。

I tried to do as : 我试图这样做:

import glob, os
def rename(dir, pattern, titlePattern):
    print('pattern', pattern)
    for pathAndFilename in glob.iglob(os.path.join(dir, pattern)):
        title, ext = os.path.splitext(os.path.basename(pathAndFilename))
        os.rename(pathAndFilename, 
                  os.path.join(dir, titlePattern % title + ext))

And then: 接着:

rename(r'/Users/Documnet/test', r'*.csv', r'file(%s)')

And i got: 我得到了:

file(newAdress).csv
file(yourInformation).csv
.

but it i need to save in the format of ( newAdress.csv -> file1.csv , yourInformation.csv -> file2.csv ): 但我需要以( newAdress.csv -> file1.csvyourInformation.csv -> file2.csv )的格式保存:

file1.csv
file2.csv
file3.csv
.
.

You should change your for loop to something like this: 您应该将for循环更改为以下内容:

for n, pathAndFilename in enumerate(glob.iglob(os.path.join(dir, pattern))):
    _, ext = os.path.splitext(os.path.basename(pathAndFilename))
    os.rename(pathAndFilename, os.path.join(dir, titlePattern.format(n+1)) + ext)

But also you should call your function as (remove the parentheses): 但是,您也应该将函数调用为(去掉括号):

rename(r'/Users/Documnet/test', r'*.csv', r'file{}')

Note I also changed the syntax since str.format is favored over the % syntax. 注意我还更改了语法,因为str.format%语法更受青睐。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM