在 Python 中读取文件内容|.PHP


Read a file's content in Python|PHP

我有100+保存omnigraffle文件,需要编写脚本才能读取然后更改其内容。

示例一:
https://www.dropbox.com/s/97cec5err3qubgq/test.graffle?dl=0

我可以通过TextMate打开它,文件的内容是xml格式

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>ActiveLayerIndex</key>
    <integer>0</integer>
    <key>ApplicationVersion</key>
    <array>
        <string>com.omnigroup.OmniGraffle6</string>
        <string>163.7.0.243167</string>
    </array>
    <key>AutoAdjust</key>
    <true/>
    <key>BackgroundGraphic</key>
    <dict>...

所以我编写代码来在 Python 中读取和写入该文件

contents = open(filename).read()
print contents

结果是

?]Ys?8~N~?֯IxgO?Gbg}?%?;)Wm?$sB
4???=?z?;F.??l??h?O????q??ش7~?z???ݓ???{??s#?8=?><?il4??Nx?????6N??o???;?hl?0?o????[XP???VF?Ӑ$d????&?????&i=????????o6??ǭN??w???????Ͷ?+/t}FF$?????
?yװ5???aWT??pT?ۥ??v??r???O??Û?u٣GR?)?I!o?~MK??|7??)[)c?'2;|@g#1?J/?!??Jo?X;ؿ??I??t%L?2Jy&?]?;)ЧC^?D????ܑ_`
????{?l?????h????]?7.?y?]7      ?&?

那么我们如何在 Python/PHP 中读取该文件呢?

您提供的链接中的文件使用 gzip 进行压缩,无论是在存储时,还是在下载时由 Dropbox 压缩以节省空间。

要么在使用文件之前对文件运行 gunzip 命令,要么使用 python gzip 模块:

import gzip
with gzip.open(filename) as f:
    contents = f.read()