python - 文件操作

 一、打开文件

1,import os

 context = "hello world!  \n you are welecome !!!"

2,f = open('hello.txt','w',encoding= 'gbk')

3,f.write(context)

4,f.close()

 

二、文件读取

    可以用readline()、readlines() 、 read()函数读取文件

1,按行读取方式readlin()

  f = open("hello.txt",'r')

 while True:

  line = f.readline()

  if line: #判断是否为空

     print(line)

      else:

     break

f.close()

2,多行读取readlines()

    使用readlines()读取文件,需要通过循环访问readlines()返回列表中的元素。

   f = open("hello.txt",'r')

  lines = f.readlines()

  for line in lines:

    print(line)

  f.close()

3,一次性读取方式read()

   读取文件最简单的方法是使用read(),将文件中所以内容读出

   f = open("hello.txt")

   context = f.read()

   print(context)

  f.close()

 

三、文件写入

    写入方法write()把字符串写入文件,writelines()方法把列表中存储的内容写入文件

 1,writelines()将列表中内容写入文件

     f  = open("hello.txt")

     li = [ "hello china \n" , "hello beijing \n" ]

    f.writelines(li)

    f.close()

四、判断文件是否存在

      if   os.path.exists("hello.txt"):

      print(" find file sucess!! ")

          os.remove("hello.txt")  #删除文件

     else:

           print("not find file !!")

五、给文件重命名

   import os

   li = os.listdir(".")   # 将当前路径文件列表

   if    "hello.txt"  in li :

  os.rename("hello.txt", "hi.txt")

  elif   "li.txt"  in li :

         os.rename("li.txt", "hello.txt")

六、文件查找

 1,findall() 文件查找

import os,sys
import re

f1 = open("shell.html",encoding='UTF-8')

count = 0
for s in f1.readlines():
li = re.findall("menu",s)
if len(li) > 0 :
count = count + li.count("menu")
print ("找到了 " + str(count) + "个menu!!!")
f1.close()

2,replace()字符串替换
f1 = open("shell.html",encoding='UTF-8')
f2 = open("shell2.html",'w',encoding="UTF-8")
for s in f1.readlines():
f2.write(s.replace("menu","menus"))

 

 

  

 

posted @ 2018-01-23 16:24  wayens  阅读(145)  评论(0)    收藏  举报