python中的文件格式

时间:2015-08-18 16:13:20

标签: python file format

我想要一个获取文件名的脚本并检查它是否是文件。 文件以.txt,.exe等结尾。 python中有任何库或模块包含 ALL 文件格式吗? 如果没有,我如何验证给定的输入(如:hey.txt,what.exe等')是一个文件? P.S我正在检查网站的文件,而不是操作系统文件(例如:“https://www.magshimim.net/App_Themes/En/images/powered_by_priza_heb.gif” 感谢所有帮助者:)

4 个答案:

答案 0 :(得分:2)

没有这样的库,因为文件格式不受限制。 我可以创建自己的.something,你也可以,文件仍然是一个正确的文件。

相反,你必须使用os.path.isfile()


正如@ zero323指出的那样,根据你的编辑,你应该使用库mimetypes

然后,如果无法猜到文件类型,请使用.guess_type()返回None

查看MIME类型here的完整列表。

答案 1 :(得分:2)

如果文件位于Web服务器上,则可以使用Content-Type标头获取文件类型。

import urllib2

urls = ['https://www.magshimim.net/App_Themes/En/images/powered_by_priza_heb.gif',
        'https://www.magshimim.net/images/magshimim_logo.png']

for url in urls:
    response = urllib2.urlopen(url)
    print url
    print response.headers.getheader('Content-type')    # Content Type
    print response.headers.getheader('Content-Length')  # Size
    print

输出应为:

https://www.magshimim.net/App_Themes/En/images/powered_by_priza_heb.gif
image/gif
1325

https://www.magshimim.net/images/magshimim_logo.png
image/png
8314

答案 2 :(得分:0)

最好的方法是使用正则表达式,因为你的脚本正在检查以下对象是否是一个文件.....如果你想检查特定文件是否存在那么使用它将是有益的os.path.isfile(路径)... 如果你对正则表达式感到满意,那么尝试创建一个正则表达式,否则让我知道我会为你创建它。 您的反馈意见将受到高度赞赏 谢谢。

答案 3 :(得分:0)

我建议:

import os.path # Use any path (ntpath, posixpath, ...) module that uses "." as an extension separator instead to be sure (if you want)

filename, ext = os.path.splitext(inputname)
# If filename and ext are both full, then it is a filename like 'something.txt'
# If only ext is there, and filename is not, then filename is something like '.bashrc' or '.ds_store'
# If there is no ext, only filename, then a file doesn't have an extension
# So:
if filename and ext: print "File", filename, "with extension", ext
elif ext and not filename:
    filename = ext; ext = ""
    print "File", filename, "with no extension!"
else: print filename, "is not a file by 'must have an extension' rule!"

您还可以使用以下内容进行检查:

c = inputname.count(".")
if c!=0 and not inputname.endswith(".") and not (inputname.startswith(".") and c==1):
    print inputname, "is a file because it has an extension!"
else: print inputname, "is not a file, no extension!"

如果你真的需要检查现有格式,那么,是的,使用mimetypes。

或谷歌周围,我看到PHP的所有格式的相当广泛的列表(作为库)。拿这个并将其转换为Python。很少有人找到并替换它。