python 学习笔记(File)

  • Open file
handle = open(filename,mode)
returns a handle use to manipulate the file. 
  • Processing files
 xfile = open('test.txt')
for cheese in xfile:
   print(cheese)
  • Counting Lines in a File
fhand = open('test.text')
count = 0
for line in fhand:
  count = count +1
print('Line Count', count)
  • Reading the 'whole' File
fhand = open('test.txt')
inp = fhand.read()
print(len(inp)
print(inp[:20])
  • Searching Through a File
fhand = open('test.txt')
for line in fhand:
  line = line.rstrip() #ignore the \n
  if line.startswith('from'):
    print(line)

alternative way

for line in fhand:
   line = line.rstrip()
   if not line.starswith('from'):
    continue
   print(line)
  • Count frenquency
counts = dict()
names = ['hello','youtube','yes','hello']
for name in names:
  if name not in counts:
    counts[name] = 1
   counts[name] = counts[name] + 1

or

counts = dict()
names = ['hello','youtube','yes','hello']
for name in names:
  counts[name] = counts.get(name,0) +1
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 矫情的话容易引起共鸣 积极向上反而就是异类
    _是可乐啊阅读 140评论 0 0
  • 文|猫石鱼 5. 付斌连忙松开了那只紧拽着杨涵的手,侧过脸看着旁边怔怔发呆的杨涵。 “把手给我,”付斌说这句话时脸...
    猫石鱼阅读 214评论 3 4
  • 在你无数的青丝中, 渐渐发现了银发的痕迹。 大学伊始的时候, 你假装坚强的挥手别离。 高考成绩出来的那刻, 你激动...
    雨天吖阅读 278评论 1 2
  • 都说每个成功的男人背后,都有一个成功的女人。何为成功的女人,我觉得成功的女人,应该是有智慧、贤惠、能相夫教子,辅导...
    张正奇阅读 625评论 1 1

友情链接更多精彩内容