文件操作

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)

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 12,160评论 0 10
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 13,473评论 0 23
  • ——.当UITabBarController 与UINavigationController 界面搭建时,从导航控...
    天序C阅读 2,701评论 0 2
  • 如果我也是个家境不错的女孩子,也许我也能成为那个性格好好的她。 如果我也是个家境不错的女孩子,也许我就不会艳羡身边...
    紫池姑娘阅读 2,615评论 0 0
  • 怀念 戈壁滩上的朝霞 2011-11-16 23:01 雁字双飞只为痴,人影齐舞心已迟。万里相逢何其难,不抵今日语...
    戈壁黄沙阅读 1,339评论 0 0