美文网首页
文件操作

文件操作

作者: 瞬间流星 | 来源:发表于2018-05-16 22:26 被阅读0次

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)

相关文章

  • 文件操作

    文件操作 目标 文件操作的作用 文件的基本操作打开读写关闭 文件备份 文件和文件夹的操作 一. 文件操作的作用 思...

  • 文件和目录处理相关

    文件和目录处理相关 题: 考点:文件操作/写入操作; 延伸:目录操作函数,其他文件操作; 文件读写操作 文件系统函...

  • 09-文件操作

    一、文件操作流程 a.普通文件操作流程: 打开文件 操作文件 关闭文件 b. json文件操作流程: open(文...

  • VBS文件操作

    VBS文件操作'操作文本文件,操作fso对象(文件对象操作) --------------------------...

  • 文件操作

    文件操作:打开文件、读写文件、操作文件内容 写入文件操作:(把大象装入冰箱)1.打开文件 ...

  • 类的补充

    一.复习 1.文件操作a.操作流程:打开文件(open),操作文件,关闭文件with open() as 文件变量...

  • 文件

    目标 文件操作的作用 文件的基本操作打开读写关闭 文件备份 文件和文件夹的操作 一. 文件操作的作用 思考:什么是...

  • 16总 正则表达式

    复习: 1.文件操作a.操作流程: 打开文件(open) --- 操作文件 --- 关闭文件(close)with...

  • 2018-09-10

    01-recode 1.文件操作a.操作流程:打开文件---》操作文件----》关闭文件with open() ...

  • 2018-09-10 day16总结

    1.文件操作 a.操作流程:打开文件(open)-操作文件-关闭文件(close)with open() as 文...

网友评论

      本文标题:文件操作

      本文链接:https://www.haomeiwen.com/subject/hommdftx.html