Python 第二天学习(文件的处理)

学习的内容是:

  • python的文件处理
  • 列表,元组,字典的使用
  • 集合的使用
  • 函数

文件file.textd的内容

A person with high EQ doesn't often criticize people.

That's because criticizing usually doesn't solve any problem.

Everybody wants to solve problems. It's just that many people don't know how. And criticizing doesn't change this.

读上述文件file.txt的代码

f = file("file.txt",'r')
#print f.readline()
line_sz = []
for line in f.readlines():
    print line
    line = line.strip("
")  ##去除换行符
    line_sz.append(line)   ##将每行的内容写到数组中
    
f.close()  ##关闭文件
print line_sz  

通过上述的代码,我可以了解到python读取文件的过程是用file打开文件(f.file("file.txt", ''r')),然后读取文件的所有内容(f.readlines),最后用循环遍历每一行。

1.关于文件处理模式

  • r 以只读的模式打开
  • w以只写的模式打开
  • a以追加的模式打开文件
  • r+b 以读写模式打开
  • w+b以写读模式打开
  • a+b以追加及读模式打开

 总结及扩展

  1. split()可以用作分隔字符串

            例如:d = "h:i:d:c:g:k"

                     print d.split(":")    -->  [h,i,d,c,g,k]

        2.strip()可以将字符串的最后指点字符删除

            例如:d = "h:i:d:c:g:k:"

                     print d.split(":")    -->  h:d:c:g:k

         

原文地址:https://www.cnblogs.com/y15821933792/p/7802076.html