Python学习笔记Coursera之PY4E学习笔记——File

Posted ivywong

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python学习笔记Coursera之PY4E学习笔记——File相关的知识,希望对你有一定的参考价值。

1、打开文件

使用handle=open(filename,mode)打开文件。这一函数将会返回一个handle(应该翻译为“柄”吧)用来操控文件,参数filename是一个字符串。参数mode是可选的,‘r‘代表读取文件,‘w‘代表写文件。

例:

>>> fhand=open(mbox.txt,r)
>>> print(fhand)
<_io.TextIOWrapper name=‘mbox.txt‘ mode=‘r‘ encoding=‘UTF-8‘>

 file handle可以看作是一个字符串序列,而文件例的每一行是这个字符串序列里的内容。

例:数文件内容的行数

fhand=open(mbox.txt)
count=0
for line in fhand:
    count=count+1
print(Line Count:,count)

$ python open.py
Line Count:132045

例:检索文件内容

fhand = open(;mbox-short.txt)
for line in fhand:
    if line.startswith(From:):
        print(line)

 

2、读取文件

使用read()来读取整个文件(包括换行符等),存入一个单独的字符串。

例:

>>> fhand=open(mbox-short.txt)
>>> inp=fhand.read()
>>> print(len(inp))
94626
>>> print(inp[:20])
From stephen.marquar

 



以上是关于Python学习笔记Coursera之PY4E学习笔记——File的主要内容,如果未能解决你的问题,请参考以下文章