简体   繁体   English

如何在python中提取带有dat扩展名的文件名?

[英]How can I extract a file name with dat extension in python?

There are many files in a folder like 文件夹中有很多文件,例如

sample-file.dat host-111.222.333.444.dat win.2k3.dat hello.micro.world.dat sample-file.dat主机111.222.333.444.dat win.2k3.dat hello.micro.world.dat

I was using split 我正在使用拆分

 file = os.path.basename(path) 
filename = file.split(".")[0]

but it does not work for all files, is there a better way to read whole filename even with dots and ignore only .dat extension 但是它不适用于所有文件,有没有更好的方法来读取整个文件名(即使带点)并且仅忽略.dat扩展名

Try 尝试

if file.endswith('.dat'):
    filename = file[:-4]

file[:-4] means get the string file and remove the last four characters file[:-4]表示获取字符串file并删除最后四个字符

Alternatively, see this question for more answers: How to replace (or strip) an extension from a filename in Python? 或者,请参见此问题以获取更多答案: 如何在Python中替换(或剥离)文件名的扩展名?

I would use rfind : 我会使用rfind

>>> s = "host-111.222.333.444.dat"
>>> filename = s[:s.rfind(".")]
>>> filename
'host-111.222.333.444'

It's like find() , but it returns the highest index. 就像find() ,但是它返回最高的索引。

Hope it helps! 希望能帮助到你!

if they have multiple points, slice and recombine with join ! 如果它们有多个点,则切片并与join重组!

file = os.path.basename(path) 
filename = ".".join(file.split(".")[:-1])

This will remove what's after the last point, without checking the content,ie 这将删除最后一点之后的内容,而不检查内容,即

  • abc => ab abc => ab
  • abdat => ab abdat => ab
  • a.exe => a a.exe => a
  • .emacs => error ? .emacs =>错误?
  • abc => abc abc => abc

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

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