码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2018-05-05 19:44:35      阅读:331      评论:0      收藏:0      [点我收藏+]

标签:参数   rap   for   strong   art   字符串   style   short   hand   

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

标签:参数   rap   for   strong   art   字符串   style   short   hand   

原文地址:https://www.cnblogs.com/IvyWong/p/8995494.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!