1. file函数
1.1 open()
fhand = open('mbox.txt')
print (fhand)
//打印地址
1.2Counting Lines in a Files
//数文件中的行数
fhand = open('mbox.txt')
count = 0
for line in fhand:
count = count +1
print ('Line count:',count)
>>>Line count: 132045
1.3 Reading the Whole File
//读取文件中的每个字符?
fhand = open('mbox-short.txt')
inp = fhand.read()
print (len(inp))
>>>94626
print (inp[:20])
>>>From stepen.marquar
1.4 Searching Through a File
fhand = open()
for line in fhand:
if line.startswith('From:')
print (line)
for line in fhand:
line = line.rstrip()
if line.stratswith('From:')
print (line)
//这个函数可以解决print函数多打空行的问题
fname = input('Enter the file name :')
//我们可以自己输入文件名字
1.5 Bad File Names
//使用try except来发现是否输入了错误的文件名
fhand = input('Enter the file name:')
try:
fhand = open(fname)
except::
print ('File cannot be opened', fname)
quit()
count = 0
for line in fhand
if line.startswith('Subject:'):
count = count +1
print ('There were ', count ,'subject lines in ', fname)