我是靠谱客的博主 妩媚帅哥,最近开发中收集的这篇文章主要介绍Python学习之文件(二),觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

文件中的read/readline/readlines函数

前面学习了关于如何读取文件的操作,但是我们发现在Python的文件帮助文档中,有很多函数,其中就有read/readline/readlines这样三个函数,那么为什么要学习这三个函数呢??
现在开始做详细解释:
read函数

help(file.read)
Help on method_descriptor:

read(…)
read([size]) -> read at most size bytes, returned as a string.

If the size argument is negative or omitted, read until EOF is reached.
Notice that when in non-blocking mode, less data than what was requested
may be returned, even if no size parameter was given.

(END)

解释: read([size]) - >读取大多数字节,以字符串形式返回。
如果指定了参数size,就按照该指定长度从文件中读取内容,否则,就读取全文。被读取出来的全文,全部塞到一个字符串里面。这样的好处就是所有的东西都在内存里面的,可以随时存取。
readline函数

help(file.readline)
Help on method_descriptor:

readline(…)
readline([size]) -> next line from the file, as a string.

Retain newline.
A non-negative size argument limits the maximum
number of bytes to return (an incomplete line may be returned then).
Return an empty string at EOF.

(END)
解释:可选参数都同read,它以行为单位返回字符串,即每次读取一行,依次循环,如果不指定size,直到最后返回的是一个空字符串。即到文件末尾。
readlines函数

help(file.readlines)
Help on method_descriptor:

readlines(…)
readlines([size]) -> list of strings, each a line from the file.

Call readline() repeatedly and return a list of the lines so read.
The optional size argument, if given, is an approximate bound on the
total number of bytes in the lines returned.

(END)
解释:它返回的是以行为单位的列表,即相当于先执行readline(),得到每一行,然后每一行中的字符串作为列表中的元素塞进一个列表中,最后将此列表返回。

开始验证以上的三个函数

所使用的文本都存放在/pythonFile/file/路径下,文件的名称为rtest.txt,文件的内容如下:
我选用了这两天爆炸与朋友圈的比特币病毒,也就是蠕虫病毒。且不管叫什么,反正是不是听着代码大师是不是很帅。当然你也可以使用python进行网络渗透,但是只建议做有意义的事哦。比如发掘漏洞并将其反馈给相关产品机构,千万不要做危害网络安全的事儿。

[root@python file]# pwd
/pythonFile/file
[root@python file]# cat rtext.txt 
What Happened to My Computer?
Your important files are encrypted.
Many of your documents,photos,videos,
databases and others are no longer
accesssible because they have been encrypted.
Maybe you are busy looking for
a wayto recover your files,
but do not waste your time.
Nobody can recover your files without our
decryption service.Can I Recover My files?
Sure,We guarantee that you can recover all
your files safely and easily,
But you have not so enouth time.
you can decrypt some of your files and free.
Try now by clicking <Decryt>.
But if you want to decrypt all
your files,you need to pay.
Your only have 3 days to submit
the payment.After that the
price will be doubled.
Also,if you don't be able to
recover your file forever.
We will have free events for user who
are so poor that they couldn't pay in 6 months.
[root@python file]# 

readline
首先使用read函数来进行操作

>>> tread = open("/pythonFile/file/rtext.txt")
>>> line = tread.read()
>>> line
"What Happened to My Computer?nYour important files are encrypted.nMany of your documents,photos,videos,ndatabases and others are no longer naccesssible because they have been encrypted.nMaybe you are busy looking forna wayto recover your files,nbut do not waste your time.nNobody can recover your files without ourndecryption service.Can I Recover My files?nSure,We guarantee that you can recover allnyour files safely and easily,nBut you have not so enouth time.nyou can decrypt some of your files and free.nTry now by clicking <Decryt>.nBut if you want to decrypt allnyour files,you need to pay.nYour only have 3 days to submitnthe payment.After that thenprice will be doubled.nAlso,if you don't be able tonrecover your file forever.nWe will have free events for user who nare so poor that they couldn't pay in 6 months.n"
>>> print line
What Happened to My Computer?
Your important files are encrypted.
Many of your documents,photos,videos,
databases and others are no longer
accesssible because they have been encrypted.
Maybe you are busy looking for
a wayto recover your files,
but do not waste your time.
Nobody can recover your files without our
decryption service.Can I Recover My files?
Sure,We guarantee that you can recover all
your files safely and easily,
But you have not so enouth time.
you can decrypt some of your files and free.
Try now by clicking <Decryt>.
But if you want to decrypt all
your files,you need to pay.
Your only have 3 days to submit
the payment.After that the
price will be doubled.
Also,if you don't be able to
recover your file forever.
We will have free events for user who
are so poor that they couldn't pay in 6 months.
>>> tread.close()
>>>

上述例子中,我们发现如果原文本中有换行,那么read( )函数在读取的时候就将换行符读取出来。再使用print函数的时候“”n“”就被自动转义换行了。

使用readline( )函数读取

>>> treadline = open("/pythonFile/file/rtext.txt")
>>> reline = treadline.readline()
>>> reline
'What Happened to My Computer?n'
>>> reline = treadline.readline()
>>> reline
'Your important files are encrypted.n'
>>> reline = treadline.readline()
>>> reline
'Many of your documents,photos,videos,n'
>>> 

每次操作一次readline( )就读取一行

这种读取好像和迭代一样,说通俗一点就是迭代。那么,既然可以这样理解,这个文件可以直接通过用循环的方式来写。

[root@python file]# cat treadline.py 
#!/usr/bin/env python
#coding:utf-8
treadline = open("/pythonFile/file/rtext.txt")
#
#
#use while loop
while True:
lineread = treadline.readline()
if not lineread:
#if returns none string,end loop
break
else:
print lineread ,
treadline.close()
[root@python file]# 

执行结果:

[root@python file]# python treadline.py 
What Happened to My Computer?
Your important files are encrypted.
Many of your documents,photos,videos,
databases and others are no longer
accesssible because they have been encrypted.
Maybe you are busy looking for
a wayto recover your files,
but do not waste your time.
Nobody can recover your files without our
decryption service.Can I Recover My files?
Sure,We guarantee that you can recover all
your files safely and easily,
But you have not so enouth time.
you can decrypt some of your files and free.
Try now by clicking <Decryt>.
But if you want to decrypt all
your files,you need to pay.
Your only have 3 days to submit
the payment.After that the
price will be doubled.
Also,if you don't be able to
recover your file forever.
We will have free events for user who
are so poor that they couldn't pay in 6 months.
[root@python file]# 

特别注意,每次对文件操作完毕,请务必关闭文件,因为文件打开后,会占用系统内存,而且误调用会消耗系统的CPU资源,当然这只是针对于一些特别大的文件,小文件并不会直接的感受的到。
使用readlines( )函数读取

>>> rlines = treadlines.readlines()
>>> rlines
['What Happened to My Computer?n', 'Your important files are encrypted.n', 'Many of your documents,photos,videos,n', 'databases and others are no longer n', 'accesssible because they have been encrypted.n', 'Maybe you are busy looking forn', 'a wayto recover your files,n', 'but do not waste your time.n', 'Nobody can recover your files without ourn', 'decryption service.Can I Recover My files?n', 'Sure,We guarantee that you can recover alln', 'your files safely and easily,n', 'But you have not so enouth time.n', 'you can decrypt some of your files and free.n', 'Try now by clicking <Decryt>.n', 'But if you want to decrypt alln', 'your files,you need to pay.n', 'Your only have 3 days to submitn', 'the payment.After that then', 'price will be doubled.n', "Also,if you don't be able ton", 'recover your file forever.n', 'We will have free events for user who n', "are so poor that they couldn't pay in 6 months.n"]
>>> treadlines = open("/pythonFile/file/rtext.txt")
>>> rlines = treadlines.readlines()
>>> for line in rlines:
...
print line,
...
What Happened to My Computer?
Your important files are encrypted.
Many of your documents,photos,videos,
databases and others are no longer
accesssible because they have been encrypted.
Maybe you are busy looking for
a wayto recover your files,
but do not waste your time.
Nobody can recover your files without our
decryption service.Can I Recover My files?
Sure,We guarantee that you can recover all
your files safely and easily,
But you have not so enouth time.
you can decrypt some of your files and free.
Try now by clicking <Decryt>.
But if you want to decrypt all
your files,you need to pay.
Your only have 3 days to submit
the payment.After that the
price will be doubled.
Also,if you don't be able to
recover your file forever.
We will have free events for user who
are so poor that they couldn't pay in 6 months.
>>> treadlines.close()

注意当中Print后面逗号的使用,如果没有逗号的话,那么将会有两个换行输出。

读取大文件

read/readline/readlines只是用来读取小文件,当然readline()也可以用while循环来读取大文件。也可以用readlin( )函数来读取大文件,但是Python为了更好的解决读取大文件不方便的问题,又引入了一个模块儿,文件输入模块儿fileinput
先来了解一下fileinput

dir(fileinput)
[‘DEFAULT_BUFSIZE’, ‘FileInput’, ‘all‘, ‘builtins‘, ‘doc‘, ‘file‘, ‘name‘, ‘package‘, ‘_state’, ‘_test’, ‘close’, ‘filelineno’, ‘filename’, ‘fileno’, ‘hook_compressed’, ‘hook_encoded’, ‘input’, ‘isfirstline’, ‘isstdin’, ‘lineno’, ‘nextfile’, ‘os’, ‘sys’]

里面包含一些属性和模块儿
来看一下Input的使用
help(fileinput.input)
Help on function input in module fileinput:

input(files=None, inplace=0, backup=”, bufsize=0, mode=’r’, openhook=None)
input([files[, inplace[, backup[, mode[, openhook]]]]])

Create an instance of the FileInput class. The instance will be used
as global state for the functions of this module, and is also returned
to use during iteration. The parameters to this function will be passed
along to the constructor of the FileInput class.

(END)

直接来测试。这个测试依然使用上面的rtext.txt文件

>>> import fileinput
>>> bigfile = fileinput.input("/pythonFile/file/rtext.txt")
>>> for text in bigfile:
...
print text,
...
What Happened to My Computer?
Your important files are encrypted.
Many of your documents,photos,videos,
databases and others are no longer
accesssible because they have been encrypted.
Maybe you are busy looking for
a wayto recover your files,
but do not waste your time.
Nobody can recover your files without our
decryption service.Can I Recover My files?
Sure,We guarantee that you can recover all
your files safely and easily,
But you have not so enouth time.
you can decrypt some of your files and free.
Try now by clicking <Decryt>.
But if you want to decrypt all
your files,you need to pay.
Your only have 3 days to submit
the payment.After that the
price will be doubled.
Also,if you don't be able to
recover your file forever.
We will have free events for user who
are so poor that they couldn't pay in 6 months.
>>> bigfile.close()

移动文件中的指针seek( )函数

help(file.seek)
Help on method_descriptor:

seek(…)
seek(offset[, whence]) -> None. Move to new file position.

Argument offset is a byte count.
Optional argument whence defaults to
0 (offset from start of file, offset should be >= 0); other values are 1
(move relative to current position, positive or negative), and 2 (move
relative to end of file, usually negative, although many platforms allow
seeking beyond the end of a file).
If the file is opened in text mode,
only offsets returned by tell() are legal.
Use of other offsets causes
undefined behavior.

:
解释:参数offset是一个字节数。可选参数whence默认为0
whence为0: 偏移量从文件开头开始,偏移量应该是大于等于0的。
whence为1如果是负数的话,表示从当前位置向前移动,如果是正数,表示从当前位置向后移动。
whence为2如果是正数的话,表示移动到文件末尾,通常使用负数,虽然许多平台允许超过文件的末尾。
在文本模式下如果打开文件,只有使用tell( )返回的偏移量是合法的。使用其它的偏移量是没有被定义的动作。
示例演示:

>>> see = open("/pythonFile/file/rtext.txt")
>>> seetext = see.readline()
>>> seetext
'What Happened to My Computer?n'
>>> seetext = see.readline()
>>> seetext
'Your important files are encrypted.n'
>>> see.seek(0)
#在这里使用了指针
>>> seetext
'Your important files are encrypted.n'
>>> seetext = see.readline()
>>> seetext
'What Happened to My Computer?n'
>>> see.close()

注意,指针seek( )里面至少要有一个给定的值,如果没有给定值,那么将会抛异常。

>>> see.seek()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: seek() takes at least 1 argument (0 given)
>>> see.close()

继续测试:

>>> see = open("/pythonFile/file/rtext.txt")
>>> seetext = see.readline()
>>> seetext
'What Happened to My Computer?n'
>>> seetext = see.readline()
>>> seetext
'Your important files are encrypted.n'
>>> see.seek(7)
>>> seetext
'Your important files are encrypted.n'
>>> seetext = see.readline()
>>> seetext
'ppened to My Computer?n'
>>> see.close()
>>> 

文件中的迭代

学习迭代前,先来看几个概念:
循环: 指在条件满足的情况下,反复执行同一段代码。
迭代:指按照某种顺序访问对象中的元素,直到满足想要的结果为止。
遍历:指满足条件的情况下,按照一定的规则访问树形结构中的每一个节点,而且每个节点只访问一次。
递归:不断重复调用自身的过程。

回顾一下前面的文件的属性和函数

dir(file)
[‘class‘, ‘delattr‘, ‘doc‘, ‘enter‘, ‘exit‘, ‘format‘, ‘getattribute‘, ‘hash‘, ‘init‘, ‘iter‘, ‘new‘, ‘reduce‘, ‘reduce_ex‘, ‘repr‘, ‘setattr‘, ‘sizeof‘, ‘str‘, ‘subclasshook‘, ‘close’, ‘closed’, ‘encoding’, ‘errors’, ‘fileno’, ‘flush’, ‘isatty’, ‘mode’, ‘name’, ‘newlines’, ‘next’, ‘read’, ‘readinto’, ‘readline’, ‘readlines’, ‘seek’, ‘softspace’, ‘tell’, ‘truncate’, ‘write’, ‘writelines’, ‘xreadlines’]

里面有一个iter,这个就是迭代。

文件中的迭代工具

迭代工具通常也被叫做迭代器,英文称iterator
依然使用文本/pythonFile/file/rtext.txt这个文本。

>>> treadlines = open("/pythonFile/file/rtext.txt")
>>> trlines = treadlines.readlines()
>>> trlines
['What Happened to My Computer?n', 'Your important files are encrypted.n', 'Many of your documents,photos,videos,n', 'databases and others are no longer n', 'accesssible because they have been encrypted.n', 'Maybe you are busy looking forn', 'a wayto recover your files,n', 'but do not waste your time.n', 'Nobody can recover your files without ourn', 'decryption service.Can I Recover My files?n', 'Sure,We guarantee that you can recover alln', 'your files safely and easily,n', 'But you have not so enouth time.n', 'you can decrypt some of your files and free.n', 'Try now by clicking <Decryt>.n', 'But if you want to decrypt alln', 'your files,you need to pay.n', 'Your only have 3 days to submitn', 'the payment.After that then', 'price will be doubled.n', "Also,if you don't be able ton", 'recover your file forever.n', 'We will have free events for user who n', "are so poor that they couldn't pay in 6 months.n"]
>>> liter = iter(trlines)
>>> liter.next()
'What Happened to My Computer?n'
>>> liter.next()
'Your important files are encrypted.n'
>>> liter.next()
'Many of your documents,photos,videos,n'
>>> liter.next()
'databases and others are no longer n'
>>> liter.next()
'accesssible because they have been encrypted.n'
>>> liter.next()
'Maybe you are busy looking forn'
>>> liter.next()
'a wayto recover your files,n'
>>> liter.next()
'but do not waste your time.n'
>>> liter.next()
'Nobody can recover your files without ourn'
>>> liter.next()
'decryption service.Can I Recover My files?n'
>>> liter.next()
'Sure,We guarantee that you can recover alln'
>>> liter.next()
'your files safely and easily,n'
>>> liter.next()
'But you have not so enouth time.n'
>>> liter.next()
'you can decrypt some of your files and free.n'
>>> liter.next()
'Try now by clicking <Decryt>.n'
>>> liter.next()
'But if you want to decrypt alln'
>>> liter.next()
'your files,you need to pay.n'
>>> liter.next()
'Your only have 3 days to submitn'
>>> liter.next()
'the payment.After that then'
>>> liter.next()
'price will be doubled.n'
>>> liter.next()
"Also,if you don't be able ton"
>>> liter.next()
'recover your file forever.n'
>>> liter.next()
'We will have free events for user who n'
>>> liter.next()
"are so poor that they couldn't pay in 6 months.n"
>>> liter.next()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
>>>treadlines.close()

一直将文本文件中的内容迭代完毕之后,出现了一个停止迭代的路径追踪。
当然,这个文本还不算很长,我是用手动的方式将文本中的内容输出完毕。但是加入文本很长,怎么做,没错,是使用循环while

>>> treadlines = open("/pythonFile/file/rtext.txt")
>>> trlines = treadlines.readlines()
>>> liter = iter(trlines)
>>> while True:
...
print liter.next(),
...
What Happened to My Computer?
Your important files are encrypted.
Many of your documents,photos,videos,
databases and others are no longer
accesssible because they have been encrypted.
Maybe you are busy looking for
a wayto recover your files,
but do not waste your time.
Nobody can recover your files without our
decryption service.Can I Recover My files?
Sure,We guarantee that you can recover all
your files safely and easily,
But you have not so enouth time.
you can decrypt some of your files and free.
Try now by clicking <Decryt>.
But if you want to decrypt all
your files,you need to pay.
Your only have 3 days to submit
the payment.After that the
price will be doubled.
Also,if you don't be able to
recover your file forever.
We will have free events for user who
are so poor that they couldn't pay in 6 months.
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
StopIteration
>>> treadlines.close()

当然迭代器并非像上面的示例一样简单,这里只是简单的举一些示例。在Python中,还可以将文本中的迭代和列表、元组互用。

>>> treadlines = open("/pythonFile/file/rtext.txt")
>>> list(treadlines)
['What Happened to My Computer?n', 'Your important files are encrypted.n', 'Many of your documents,photos,videos,n', 'databases and others are no longer n', 'accesssible because they have been encrypted.n', 'Maybe you are busy looking forn', 'a wayto recover your files,n', 'but do not waste your time.n', 'Nobody can recover your files without ourn', 'decryption service.Can I Recover My files?n', 'Sure,We guarantee that you can recover alln', 'your files safely and easily,n', 'But you have not so enouth time.n', 'you can decrypt some of your files and free.n', 'Try now by clicking <Decryt>.n', 'But if you want to decrypt alln', 'your files,you need to pay.n', 'Your only have 3 days to submitn', 'the payment.After that then', 'price will be doubled.n', "Also,if you don't be able ton", 'recover your file forever.n', 'We will have free events for user who n', "are so poor that they couldn't pay in 6 months.n"]
>>> tuple(treadlines)
()
#为什么什么都没有返回???
>>> treadlines.close()

上述示例中tuple并没有返回任何值,是因为先进行了List操作,文件中的指针已经指向文件的末尾了,所以tuple没有输出任何内容。如果重新让其输出,则需要重新给对象赋值。
如下:

>>> treadlines = open("/pythonFile/file/rtext.txt")
>>> tuple(treadlines)
('What Happened to My Computer?n', 'Your important files are encrypted.n', 'Many of your documents,photos,videos,n', 'databases and others are no longer n', 'accesssible because they have been encrypted.n', 'Maybe you are busy looking forn', 'a wayto recover your files,n', 'but do not waste your time.n', 'Nobody can recover your files without ourn', 'decryption service.Can I Recover My files?n', 'Sure,We guarantee that you can recover alln', 'your files safely and easily,n', 'But you have not so enouth time.n', 'you can decrypt some of your files and free.n', 'Try now by clicking <Decryt>.n', 'But if you want to decrypt alln', 'your files,you need to pay.n', 'Your only have 3 days to submitn', 'the payment.After that then', 'price will be doubled.n', "Also,if you don't be able ton", 'recover your file forever.n', 'We will have free events for user who n', "are so poor that they couldn't pay in 6 months.n")
>>> treadlines.close()

关于文件操作的内容,暂时学习这么多,从明天开始学习函数。

函数的内容多也很重要,好好学习。加油。

2017年05月14日
下午15:19

最后

以上就是妩媚帅哥为你收集整理的Python学习之文件(二)的全部内容,希望文章能够帮你解决Python学习之文件(二)所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(52)

评论列表共有 0 条评论

立即
投稿
返回
顶部