在python中提取值/重命名文件名 [英] extract values/renaming filename in python

查看:174
本文介绍了在python中提取值/重命名文件名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用python重命名包含以下值的文件名:~test1~test2~filename.csv

I am trying to use python to rename a filename which contains values such as: ~test1~test2~filename.csv

我想将文件重命名为filename.csv.波浪号是我的前两个单词的分隔符,并且我不想在结局文件名中使用这些单词.这些词是变量.任何援助将不胜感激.谢谢!

I want to rename the file to filename.csv. The tildes being my separator for the first two words, and I do not want those words in my finale file name. These words are variables. Any assistance would be appreciated. Thanks!

推荐答案

由于每个文件名的单词都会更改,因此最好在目录中搜索与模式匹配的文件. glob 为您做到这一点.

Since the words change for each file name its best to search a directory for files that match a pattern. glob does that for you.

如果您有这样的目录:

.
├── ~a~b~c.csv
├── file.csv
├── ~foo~bar~f1.csv
└── hello.txt

然后运行:

import os, glob
for f in glob.glob('~*~*~*.csv'):
    os.rename(f,f.split('~')[-1])

会给您:

.
├── c.csv
├── f1.csv
├── file.csv
└── hello.txt

这篇关于在python中提取值/重命名文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆