问题:如何检查文件的扩展名?
我正在某个程序上工作,根据文件的扩展名,我需要做不同的事情。我可以用这个吗?
if m == *.mp3
...
elif m == *.flac
...
I’m working on a certain program where I need to do different things depending on the extension of the file. Could I just use this?
if m == *.mp3
...
elif m == *.flac
...
回答 0
假设m
是一个字符串,可以使用endswith
:
if m.endswith('.mp3'):
...
elif m.endswith('.flac'):
...
要不区分大小写并消除可能很大的else-if链:
m.lower().endswith(('.png', '.jpg', '.jpeg'))
Assuming m
is a string, you can use endswith
:
if m.endswith('.mp3'):
...
elif m.endswith('.flac'):
...
To be case-insensitive, and to eliminate a potentially large else-if chain:
m.lower().endswith(('.png', '.jpg', '.jpeg'))
回答 1
os.path
提供了许多用于处理路径/文件名的功能。(docs)
os.path.splitext
采用路径并将文件扩展名从其末尾分割。
import os
filepaths = ["/folder/soundfile.mp3", "folder1/folder/soundfile.flac"]
for fp in filepaths:
# Split the extension from the path and normalise it to lowercase.
ext = os.path.splitext(fp)[-1].lower()
# Now we can simply use == to check for equality, no need for wildcards.
if ext == ".mp3":
print fp, "is an mp3!"
elif ext == ".flac":
print fp, "is a flac file!"
else:
print fp, "is an unknown file format."
给出:
/folder/soundfile.mp3是mp3!
folder1 / folder / soundfile.flac是一个flac文件!
os.path
provides many functions for manipulating paths/filenames. (docs)
os.path.splitext
takes a path and splits the file extension from the end of it.
import os
filepaths = ["/folder/soundfile.mp3", "folder1/folder/soundfile.flac"]
for fp in filepaths:
# Split the extension from the path and normalise it to lowercase.
ext = os.path.splitext(fp)[-1].lower()
# Now we can simply use == to check for equality, no need for wildcards.
if ext == ".mp3":
print fp, "is an mp3!"
elif ext == ".flac":
print fp, "is a flac file!"
else:
print fp, "is an unknown file format."
Gives:
/folder/soundfile.mp3 is an mp3!
folder1/folder/soundfile.flac is a flac file!
回答 2
pathlib
从Python3.4开始使用。
from pathlib import Path
Path('my_file.mp3').suffix == '.mp3'
Use pathlib
From Python3.4 onwards.
from pathlib import Path
Path('my_file.mp3').suffix == '.mp3'
回答 3
查看模块fnmatch。那会做你想做的。
import fnmatch
import os
for file in os.listdir('.'):
if fnmatch.fnmatch(file, '*.txt'):
print file
Look at module fnmatch. That will do what you’re trying to do.
import fnmatch
import os
for file in os.listdir('.'):
if fnmatch.fnmatch(file, '*.txt'):
print file
回答 4
一种简单的方法可能是:
import os
if os.path.splitext(file)[1] == ".mp3":
# do something
os.path.splitext(file)
将返回具有两个值的元组(不带扩展名的文件名+仅带扩展名的文件名)。因此,第二个索引([1])仅给您扩展名。很棒的事情是,如果需要,您还可以通过这种方式很容易地访问文件名!
one easy way could be:
import os
if os.path.splitext(file)[1] == ".mp3":
# do something
os.path.splitext(file)
will return a tuple with two values (the filename without extension + just the extension). The second index ([1]) will therefor give you just the extension. The cool thing is, that this way you can also access the filename pretty easily, if needed!
回答 5
也许:
from glob import glob
...
for files in glob('path/*.mp3'):
do something
for files in glob('path/*.flac'):
do something else
or perhaps:
from glob import glob
...
for files in glob('path/*.mp3'):
do something
for files in glob('path/*.flac'):
do something else
回答 6
旧线程,但可能会帮助将来的读者…
如果没有其他原因,我会避免在文件名上使用.lower(),除了使您的代码与平台更独立外。(Linux的是情况下sensistive,.lower()上的一个文件名必定破坏你的逻辑最终…或者更糟,一个重要的文件!)
为什么不使用re?(尽管要更加健壮,您应该检查每个文件的魔术文件头…
如何检查在python中没有扩展名的文件的类型?)
import re
def checkext(fname):
if re.search('\.mp3$',fname,flags=re.IGNORECASE):
return('mp3')
if re.search('\.flac$',fname,flags=re.IGNORECASE):
return('flac')
return('skip')
flist = ['myfile.mp3', 'myfile.MP3','myfile.mP3','myfile.mp4','myfile.flack','myfile.FLAC',
'myfile.Mov','myfile.fLaC']
for f in flist:
print "{} ==> {}".format(f,checkext(f))
输出:
myfile.mp3 ==> mp3
myfile.MP3 ==> mp3
myfile.mP3 ==> mp3
myfile.mp4 ==> skip
myfile.flack ==> skip
myfile.FLAC ==> flac
myfile.Mov ==> skip
myfile.fLaC ==> flac
An old thread, but may help future readers…
I would avoid using .lower() on filenames if for no other reason than to make your code more platform independent. (linux is case sensistive, .lower() on a filename will surely corrupt your logic eventually …or worse, an important file!)
Why not use re? (Although to be even more robust, you should check the magic file header of each file…
How to check type of files without extensions in python? )
import re
def checkext(fname):
if re.search('\.mp3$',fname,flags=re.IGNORECASE):
return('mp3')
if re.search('\.flac$',fname,flags=re.IGNORECASE):
return('flac')
return('skip')
flist = ['myfile.mp3', 'myfile.MP3','myfile.mP3','myfile.mp4','myfile.flack','myfile.FLAC',
'myfile.Mov','myfile.fLaC']
for f in flist:
print "{} ==> {}".format(f,checkext(f))
Output:
myfile.mp3 ==> mp3
myfile.MP3 ==> mp3
myfile.mP3 ==> mp3
myfile.mp4 ==> skip
myfile.flack ==> skip
myfile.FLAC ==> flac
myfile.Mov ==> skip
myfile.fLaC ==> flac
回答 7
import os
source = ['test_sound.flac','ts.mp3']
for files in source:
fileName,fileExtension = os.path.splitext(files)
print fileExtension # Print File Extensions
print fileName # It print file name
import os
source = ['test_sound.flac','ts.mp3']
for files in source:
fileName,fileExtension = os.path.splitext(files)
print fileExtension # Print File Extensions
print fileName # It print file name
回答 8
if (file.split(".")[1] == "mp3"):
print "its mp3"
elif (file.split(".")[1] == "flac"):
print "its flac"
else:
print "not compat"
if (file.split(".")[1] == "mp3"):
print "its mp3"
elif (file.split(".")[1] == "flac"):
print "its flac"
else:
print "not compat"
回答 9
#!/usr/bin/python
import shutil, os
source = ['test_sound.flac','ts.mp3']
for files in source:
fileName,fileExtension = os.path.splitext(files)
if fileExtension==".flac" :
print 'This file is flac file %s' %files
elif fileExtension==".mp3":
print 'This file is mp3 file %s' %files
else:
print 'Format is not valid'
#!/usr/bin/python
import shutil, os
source = ['test_sound.flac','ts.mp3']
for files in source:
fileName,fileExtension = os.path.splitext(files)
if fileExtension==".flac" :
print 'This file is flac file %s' %files
elif fileExtension==".mp3":
print 'This file is mp3 file %s' %files
else:
print 'Format is not valid'
回答 10
file='test.xlsx'
if file.endswith('.csv'):
print('file is CSV')
elif file.endswith('.xlsx'):
print('file is excel')
else:
print('none of them')
file='test.xlsx'
if file.endswith('.csv'):
print('file is CSV')
elif file.endswith('.xlsx'):
print('file is excel')
else:
print('none of them')