简体   繁体   English

如何从文件名中删除点而不从扩展名中删除它们?

[英]How to remove dots from a filename without removing them from the extension?

I am iterating through a folder that has files of different extensions.我正在遍历一个包含不同扩展名文件的文件夹。 I want to remove dots ( '.' ) from the filename, but not the extension .我想从文件名中删除点( '.' ),而不是扩展名 If I simply do this:如果我只是这样做:

def filename_replacer(file_name):
    extension = file_name[-4:]
    raw_name = file_name[:-4]       
    new_name = raw_name.replace(".", "_")
    new_name = new_name + extension
    return new_name

file = "Remove.TheDotReport.xlsx"
cleaned_file = filename_replacer(file)

It comes out incorrect (ex: Remove_TheDotReport_xlxs ).结果不正确(例如: Remove_TheDotReport_xlxs )。 How can I consistently remove the dots in the file without messing up the extension?如何在不弄乱扩展名的情况下一致地删除文件中的点?

Use os.path.splitext to get the extension out first.首先使用os.path.splitext获取扩展。

import os

def filename_replacer(filename):
  fname, fext = os.path.splitext(filename)
  return fname.replace(".", "_") + fext

Since Python 3.4, a convenient way for working with paths is the pathlib built-in library.从 Python 3.4 开始,使用pathlib内置库的便捷方法是。 It treats paths as objects instead of simple strings .它将路径视为对象而不是简单的字符串

Since Python 3.9, a new method was added - with_stem - which only changes the name of the file without the extension.从 Python 3.9 开始,添加了一个新方法 - with_stem - 它只更改文件名而不更改扩展名。 So this can be done quite easily:所以这可以很容易地完成:

from pathlib import Path

path = Path("Remove.TheDotReport.xlsx")
print(path.with_stem(path.stem.replace('.', '_')))
# Remove_TheDotReport.xlsx

For older versions, you can still use the with_name method with a bit more work (adding the extension separately):对于旧版本,您仍然可以使用with_name方法进行更多工作(单独添加扩展名):

from pathlib import Path

path = Path("Remove.TheDotReport.xlsx")
print(path.with_name(path.stem.replace('.', '_') + path.suffix))
# Remove_TheDotReport.xlsx

This is for a bash script to remove dots from the filename and keep the extension dot if you want to change for anyone file ( 'dir /b *.filename' ) give filename here.这是一个 bash 脚本从文件名中删除点并保留扩展点,如果你想更改任何文件( 'dir /b *.filename' )在这里给出文件名。

@echo off
for /f "delims=" %%a in ('dir /b *') do call :dot "%%a"
pause
goto :EOF
:dot
set "var=%~n1"
set "var=%var:.= %"
ren %1 "%var%%~x1"

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

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