How to check type of files without extensions in p

2019-01-01 15:34发布

I have a folder full of files and these doesn't have an extension. How can I check file types? I want to check the file type and change the filename accordingly. Let's assume a function filetype(x) returns file type like png. I want to do this:

files = os.listdir(".")
for f in files:
    os.rename(f, f+filetype(f))

How do I do this?

7条回答
君临天下
2楼-- · 2019-01-01 16:04

On unix and linux there is the file command to guess file types. There's even a windows port.

From the man page:

File tests each argument in an attempt to classify it. There are three sets of tests, performed in this order: filesystem tests, magic number tests, and language tests. The first test that succeeds causes the file type to be printed.

You would need to run the file command with the subprocess module and then parse the results to figure out an extension.

edit: Ignore my answer. Use Chris Johnson's answer instead.

查看更多
登录 后发表回答