文本操做小结

文本操做:
 对文件操作流程:
 1. 打开文件,得到文件句柄并赋值给一个变量
 2. 通过句柄对文件进行操作
 3. 关闭文件
 
 data = open("file").read()
 print(data)
 
 fs = open("yesterday","r", encoding="utf-8")         #fs即文件句柄
 data = fs.read()          #从头开始一行一行读文件内容,然后指针到了最后。
 data2 = fs.read()             #指针到了最后,再读是没有内容的。
 print(data)
 print("=" * 60)
 print(data2)
 
 
 模式:
 r  :   #只读
 w  :   #只写
 a  :   #追加也不能读
 r+ :   #读写,能读能写(写是追加的功能,写在最后面)
 w+  :   #写读,能写能读(写是追加的功能,写在最后面)
 a+ :   #追加读,能写能读(写是追加的功能,写在最后面)
 rb :   #以二进制编码格式读文件
 wb :   #以二进制编码格式写文件
 ab :   以二进制编码格式追加写文件
 
 bytes 和 str 使用decode
 str 和 bytes 使用encode
 
 f.write("我爱北京天安门\n") 
 f.write("天安门上天阳升")
 f.close       #文件关闭
 
 f.tell()      #按照字符数连计数的
 with open("yesterday", "r", encoding="utf-8") as fs:
  print(fs.tell())   #输出:0
  fs.read(10)
  print(fs.tell())   #输出:10
  
 with open("yesterday", "r", encoding="utf-8") as fs:
  print(fs.tell())   #输出:0
  fs.readline()
  print(fs.tell())   #输出:31 
  
 f.seek(0)      #回到0字符的位置
 with open("yesterday", "r", encoding="utf-8") as fs:
  print(fs.tell())   #输出:0
  fs.readline()
  print(fs.tell())   #输出:31
  fs.readline()
  print(fs.tell())   #输出:60
  fs.seek(31)     #指针回到31  
  fs.readline()
  print(fs.tell())   #输出:60
  
 f.encoding()     #返回编码
 f.truncate(20)     #截取20个字符
 
 fs.read()      #全部读取
 fs.readline()     #读取一行    
 fs.readline(5)     #读取一行的前5个字符
 fs.readlines()     #将每一行作为一个列表元素读取
 
 
 对于大数据文本的读取,例如一个20GB的文本
 with open("yesterday", "r", encoding="utf-8") as fs:
  for line in fs:    #从对象中循环读取
   print(line)
   
 最有效率的读取大文件
 
 进度条的使用:
 import sys,time
 for i in range(100):
  sys.stdout.write("#")
  sys.stdout.flush()
  time.sleep(0.1)
 
 
 为了避免打开文件后忘记关闭,可以通过管理上下文,即
 with open("yesterday", "r") as f:
 
 打开多个文件(一行代码不要超过80个字符)
 with open("yesterday", "r") as f1,with open("yesterday", "r") as f2:
 
 
 
 文件的修改:
 
 程序练习:
 
 实现简单的shell sed替换功能:
 
 import sys
 file_name = sys.argv[1]
 find_str = sys.argv[2]
 replace_str = sys.argv[3]
 
 f=""
 with open(file_name, "r") as fs1:
  for n in fs1:
   f += n.replace(find_str, replace_str)
   
 with open(file_name, "w") as fs2:
  fs2.write(f)
  fs2.flush()

猜你喜欢

转载自www.cnblogs.com/brace2011/p/9185429.html