【问题标题】:Replacing Punctuation in List of Files替换文件列表中的标点符号
【发布时间】:2020-09-25 22:10:07
【问题描述】:

我正在尝试替换 '. ' 对于目录中的所有文件,都带有一个 '_'。文件如下所示:

000. utm_homescreen.bak
000. utm_homescreen.yxwz
001. utm_chain_screen.bak
001. utm_chain_screen.yxwz
...

现在我正在尝试对目录中的每个文件应用拆分和连接,但我没有看到这些更改反映在文件名中。

from pathlib import Path

for file in Path('..').glob('*'):
    if not file.is_dir():
        '_'.join(file.name.split('. '))

【问题讨论】:

  • 看看Path.rename,现在你只是在制作str,并没有用它做任何事情。

标签: python string file pathlib


【解决方案1】:

我最终像这样使用 Path.rename():

for file in Path('..').glob('*'):
    if not file.is_dir():
        file.rename('_'.join(str(file).split('. ')))

感谢您的回复。

【讨论】:

    【解决方案2】:

    您忘记使用重命名功能?我没跑但是应该是这样的

    像马里奥·伊沙克建议的那样改变

    from pathlib import Path
    
    for file in Path('..').glob('*'):
        if not file.is_dir():
            Path(file.name).rename('_'.join(file.name.split('. ')))
    

    【讨论】:

    • 应该使用Path.rename,因为无论如何pathlib都在使用。
    【解决方案3】:

    尝试使用os.rename()replace()

    from os, glob
    for file in glob.glob('*'): # list of all files in the folder
        if not file.is_dir():
            os.rename(file,file.replace('. ','_')) # rename the file with '. ' replaced with '_'
    

    【讨论】:

      猜你喜欢
      • 2014-03-07
      • 1970-01-01
      • 2022-11-29
      • 2021-10-05
      • 1970-01-01
      • 1970-01-01
      • 2021-09-19
      • 2014-01-01
      • 1970-01-01
      相关资源
      最近更新 更多