使用python批量搜索并替换文件名中的字符串

发布于 2024-12-11 12:53:25 字数 665 浏览 0 评论 0原文

我正在尝试编写一个小的 python 脚本,通过搜索和替换来重命名一堆文件名。例如:

原始文件名: MyMusic.Songname.Artist-mp3.iTunes.mp3

意图结果: Songname.Artist.mp3

到目前为止我得到的是:(

#!/usr/bin/env python
from os import rename, listdir

mustgo = "MyMusic."
filenames = listdir('.')

for fname in fnames:
  if fname.startswith(mustgo):
    rename(fname, fname.replace(mustgo, '', 1))

据我所知是从这个网站得到的)

无论如何,这只会删除开头的字符串,但不会删除文件名中的字符串。

另外,我想使用一个单独的文件(例如 badwords.txt),其中包含应搜索和替换的所有字符串,以便我可以更新它们而无需编辑整个代码。

Content of badwords.txt
MyMusic.
-mp3
-MP3
.iTunes
.itunes

我已经寻找了很长一段时间但还没有找到任何东西。将不胜感激任何帮助!

谢谢你!

I am trying to write a small python script to rename a bunch of filenames by searching and replacing. For example:

Original filename:
MyMusic.Songname.Artist-mp3.iTunes.mp3

Intendet Result:
Songname.Artist.mp3

what i've got so far is:

#!/usr/bin/env python
from os import rename, listdir

mustgo = "MyMusic."
filenames = listdir('.')

for fname in fnames:
  if fname.startswith(mustgo):
    rename(fname, fname.replace(mustgo, '', 1))

(got it from this site as far as i can remember)

Anyway, this will only get rid of the String at the beginning, but not of those in the filename.

Also I would like to maybe use a seperate file (eg badwords.txt) containing all the strings that should be searched for and replaced, so that i can update them without having to edit the whole code.

Content of badwords.txt
MyMusic.
-mp3
-MP3
.iTunes
.itunes

I have been searching for quite some time now but havent found anything. Would appreciate any help!

Thank you!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

横笛休吹塞上声 2024-12-18 12:53:25
import fnmatch
import re    
import os

with open('badwords.txt','r') as f:
    pat='|'.join(fnmatch.translate(badword)[:-1] for badword in 
                 f.read().splitlines())   

for fname in os.listdir('.'):
    new_fname=re.sub(pat,'',fname)
    if fname != new_fname:
        print('{o} --> {n}'.format(o=fname,n=new_fname))
        os.rename(fname, new_fname)

# MyMusic.Songname.Artist-mp3.iTunes.mp3 --> Songname.Artist.mp3
  • 请注意,某些文件可能会被覆盖(因此
    丢失)如果两个名称在之后减少为相同的缩写名称
    坏词已被删除。可以保留一组新的 fname
    在调用 os.rename 之前进行检查以防止丢失数据
    名称冲突。
  • fnmatch.translate 采用 shell 样式模式并返回
    等价的正则表达式。上面是用来转换坏词的
    (例如'.iTunes')转换为正则表达式(例如r'\.iTunes')。
  • 您的坏词列表似乎表明您想忽略大小写。你
    可以通过将 '(?i)' 添加到 pat 的开头来忽略大小写:

    with open('badwords.txt','r') as f:
       pat='(?i)'+'|'.join(fnmatch.translate(badword)[:-1] 中的坏词 
                           f.read().splitlines())
    
import fnmatch
import re    
import os

with open('badwords.txt','r') as f:
    pat='|'.join(fnmatch.translate(badword)[:-1] for badword in 
                 f.read().splitlines())   

for fname in os.listdir('.'):
    new_fname=re.sub(pat,'',fname)
    if fname != new_fname:
        print('{o} --> {n}'.format(o=fname,n=new_fname))
        os.rename(fname, new_fname)

# MyMusic.Songname.Artist-mp3.iTunes.mp3 --> Songname.Artist.mp3
  • Note that it is possible for some files to be overwritten (and thus
    lost) if two names get reduced to the same shortened name after
    badwords have been removed. A set of new fnames could be kept and
    checked before calling os.rename to prevent losing data through
    name collisions.
  • fnmatch.translate takes shell-style patterns and returns the
    equivalent regular expression. It is used above to convert badwords
    (e.g. '.iTunes') into regular expressions (e.g. r'\.iTunes').
  • Your badwords list seems to indicate you want to ignore case. You
    could ignore case by adding '(?i)' to the beginning of pat:

    with open('badwords.txt','r') as f:
       pat='(?i)'+'|'.join(fnmatch.translate(badword)[:-1] for badword in 
                           f.read().splitlines())
    
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文