[英]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中替换(或剥离)文件名的扩展名?
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 这将删除最后一点之后的内容,而不检查内容,即
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.