关于人工智能:Python文件和操作系统基础

文章和代码等曾经归档至【Github仓库:https://github.com/timerring/dive-into-AI 】或者【AIShareLab】回复 python数据分析 也可获取。

文件和操作系统

代码示例大多应用诸如 pandas.read_csv 之类的高级工具将磁盘上的数据文件读入Python数据结构。但咱们还是须要理解一些无关 Python 文件解决方面的基础知识。

为了关上一个文件以便读写,能够应用内置的open函数以及一个绝对或相对的文件门路:

In [207]: path = 'examples/segismundo.txt'

In [208]: f = open(path)

默认状况下,文件是以只读模式(’r’)关上的。而后,咱们就能够像解决列表那样来解决这个文件句柄f了,比方对行进行迭代:

for line in f:
    pass

从文件中取出的行都带有残缺的行结束符(EOL),因而你经常会看到上面这样的代码(失去一组没有EOL的行):

In [209]: lines = [x.rstrip() for x in open(path)]

In [210]: lines
Out[210]: 
['Sueña el rico en su riqueza,',
 'que más cuidados le ofrece;',
 '',
 'sueña el pobre que padece',
 'su miseria y su pobreza;',
 '',
 'sueña el que a medrar empieza,',
 'sueña el que afana y pretende,',
 'sueña el que agravia y ofende,',
 '',
 'y en el mundo, en conclusión,',
 'todos sueñan lo que son,',
 'aunque ninguno lo entiende.',
 '']

如果应用open创立文件对象,肯定要用close敞开它。敞开文件能够返回操作系统资源:

In [211]: f.close()

with语句能够更容易地清理关上的文件

In [212]: with open(path) as f:
   .....:     lines = [x.rstrip() for x in f]

这样能够在退出代码块时,主动敞开文件。

如果输出f =open(path,’w’),就会有一个新文件被创立在examples/segismundo.txt,并笼罩掉该地位原来的任何数据。另外有一个x文件模式,它能够创立可写的文件,然而如果文件门路存在,就无奈创立。表3-3列出了所有的读/写模式。

对于可读文件,一些罕用的办法是read、seek和tell。read会从文件返回字符。字符的内容是由文件的编码决定的(如UTF-8),如果是二进制模式关上的就是原始字节:

In [213]: f = open(path)

In [214]: f.read(10)
Out[214]: 'Sueña el r'

In [215]: f2 = open(path, 'rb')  # Binary mode

In [216]: f2.read(10)
Out[216]: b'Sue\xc3\xb1a el '

read模式会将文件句柄的地位提前,提前的数量是读取的字节数。tell能够给出以后的地位:

In [217]: f.tell()
Out[217]: 11

In [218]: f2.tell()
Out[218]: 10

只管咱们从文件读取了10个字符,地位却是11,这是因为用默认的编码用了这么多字节才解码了这10个字符。你能够用sys模块查看默认的编码:

In [219]: import sys

In [220]: sys.getdefaultencoding()
Out[220]: 'utf-8'

seek将文件地位更改为文件中的指定字节:

In [221]: f.seek(3)
Out[221]: 3

In [222]: f.read(1)
Out[222]: 'ñ'

最初,敞开文件:

In [223]: f.close()

In [224]: f2.close()

向文件写入,能够应用文件的write或writelines办法。例如,咱们能够创立一个无空行版的prof_mod.py:

In [225]: with open('tmp.txt', 'w') as handle:
   .....:     handle.writelines(x for x in open(path) if len(x) > 1)

In [226]: with open('tmp.txt') as f:
   .....:     lines = f.readlines()

In [227]: lines
Out[227]: 
['Sueña el rico en su riqueza,\n',
 'que más cuidados le ofrece;\n',
 'sueña el pobre que padece\n',
 'su miseria y su pobreza;\n',
 'sueña el que a medrar empieza,\n',
 'sueña el que afana y pretende,\n',
 'sueña el que agravia y ofende,\n',
 'y en el mundo, en conclusión,\n',
 'todos sueñan lo que son,\n',
 'aunque ninguno lo entiende.\n']

表3-4列出了一些最罕用的文件办法。

文件的字节和Unicode

Python文件的默认操作是“文本模式”,也就是说,你须要解决Python的字符串(即Unicode)。它与“二进制模式”绝对,文件模式加一个b。咱们来看上一节的文件(UTF-8编码、蕴含非ASCII字符):

In [230]: with open(path) as f:
   .....:     chars = f.read(10)

In [231]: chars
Out[231]: 'Sueña el r'

UTF-8是长度可变的Unicode编码,所以当我从文件申请肯定数量的字符时,Python会从文件读取足够多(可能少至10或多至40字节)的字节进行解码。如果以“rb”模式关上文件,则读取确切的申请字节数:

In [232]: with open(path, 'rb') as f:
   .....:     data = f.read(10)

In [233]: data
Out[233]: b'Sue\xc3\xb1a el '

取决于文本的编码,你能够将字节解码为str对象,但只有当每个编码的Unicode字符都齐全成形时能力这么做:

In [234]: data.decode('utf8')
Out[234]: 'Sueña el '

In [235]: data[:4].decode('utf8')
---------------------------------------------------------------------------
UnicodeDecodeError                        Traceback (most recent call last)
<ipython-input-235-300e0af10bb7> in <module>()
----> 1 data[:4].decode('utf8')
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc3 in position 3: unexpecte
d end of data

文本模式联合了open的编码选项,提供了一种更不便的办法将Unicode转换为另一种编码:

In [236]: sink_path = 'sink.txt'

In [237]: with open(path) as source:
   .....:     with open(sink_path, 'xt', encoding='iso-8859-1') as sink:
   .....:         sink.write(source.read())

In [238]: with open(sink_path, encoding='iso-8859-1') as f:
   .....:     print(f.read(10))
Sueña el r

留神,不要在二进制模式中应用seek。如果文件地位位于定义Unicode字符的字节的两头地位,读取前面会产生谬误:

In [240]: f = open(path)

In [241]: f.read(5)
Out[241]: 'Sueña'

In [242]: f.seek(4)
Out[242]: 4

In [243]: f.read(1)
---------------------------------------------------------------------------
UnicodeDecodeError                        Traceback (most recent call last)
<ipython-input-243-7841103e33f5> in <module>()
----> 1 f.read(1)
/miniconda/envs/book-env/lib/python3.6/codecs.py in decode(self, input, final)
    319         # decode input (taking the buffer into account)
    320         data = self.buffer + input
--> 321         (result, consumed) = self._buffer_decode(data, self.errors, final
)
    322         # keep undecoded input until the next call
    323         self.buffer = data[consumed:]
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb1 in position 0: invalid s
tart byte

In [244]: f.close()

如果你常常要对非ASCII字符文本进行数据分析,精通Python的Unicode性能是十分重要的。更多内容,参阅Python官网文档。

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理