用Python在Mac上打开.pages文件
我想打开一个这样的Pages文档:
directory = "/Path/to/file/"
with open(directory+"test.pages") as file:
data = f.readlines()
for line in data:
words = line.split()
print words
然后我遇到了这个错误:
IOError: [Errno 21] Is a directory: '/path/to/file/test.pages'
为什么它会被认为是一个文件夹?那我该怎么打开它呢?
2 个回答
0
我有一台运行OSX 10.9.3的Macbook Pro。
我用了你的代码,但我没有遇到你提到的问题。因为你要打开一个.pages
文件,所以你需要先对这个文件进行解码:
File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/encodings/ascii.py", line 26, in decode
return codecs.ascii_decode(input, self.errors)[0]
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 10: ordinal not in range(128)
1
'/path/to/file/test.pages'
是你电脑上的一个文件夹,所以在Python中无法直接打开。你的操作系统把这个文件夹里的几个文件打包在一起,可能把它当成一个整体来展示。你可以尝试浏览这个文件夹,看看里面有什么内容:
for root, dirs, files in os.walk('/path/to/file/test.pages'):
for file in files:
print os.path.join(root, file)
但是直接打开这些文件并试图读取里面的内容,可能不会有什么结果。
我会教你怎么尝试找出里面是否有纯文本:
import re
# use a pattern that matches for any letter A-Z, upper and lower, 0-9, and _
pattern = re.compile(r'.*\w+.*')
for root, dirs, files in os.walk('/path/to/file/test.pages'):
for file in files:
# open each file with the context manager so it's automatically closed
# regardless if there's an error. Use the Universal Newlines (U) flag too
# as a best practice (Unix, Linux, and MS have different newlines).
with open(os.path.join(root, file), 'rU') as f:
for line in f:
if re.match(pattern, line):
print line