【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

猜你喜欢

转载自www.cnblogs.com/IvyWong/p/8995494.html
今日推荐