Python 文件操作

来源:互联网 发布:计算机美工专业 编辑:程序博客网 时间:2024/05/29 13:12
演示文件的创建, 写入和关闭的操作

context = " hello world"
f = file('hello.txt', 'w')
f.write(context)
f.close()

可以使用open 来代替file , open 是file 的别名

文件的读取:

 文件中读取的方法有很多种, 可以使用readline, readlines 或者 read 函数读取文件。

 # 如果不存在就创建hello.txt  演示readline 的使用方法

f = open("hello.txt")
while True:
    line = f.readline()
    if line:
        print line
    else:
        break
f.close()

#演示多行的读取

f = file('hello.txt')
lines = f.readlines()
for line in lines:
    print line

根据结果判断, 所有的行已经被读入到内存了。

# 文件的写入
f = file("hello.txt", "w+")
li = ["hello world\n", "hello china\n"]
f.writelines(li)
f.close()

结果和明显, 如果原来的文件里面有内容, 则清空文件当中的所有内容,重新写入

# 文件的追加
f = file("hello.txt", "a+")
new_context = "goodbye"
f.write(new_context)
f.close()


#文件的删除, 文件的删除需要使用os模块哦以及os.path 模块, os模块提供了系统对环境,文件目录的等操作的借口函数
#需要注意的是,  os 当中的file  open 函数与内建的函数使用的方法不同

import os

file("hello.txt","w")
if os.path.exists("hello.txt"):
    os.remove("hello.txt")

#文件的复制
#file 类中没有提供直接复制文件的方法, 但是可以使用read write 方法模拟实现文件拷贝的功能
#把文件hello.txt 文件的内容复制到hello2.txt 文件中

src = file("hello.txt","w")
li = ["hello world \n", "hello dezhou\n"]
src.writelines(li)
src.close()

src = file("hello.txt","r")
dst = file("hello2.txt","w")
dst.write(src.read())
src.close()
dst.close()

#使用shutil 模块实现文件拷贝
import shutil

shutil.copyfile("hello.txt","hello3.txt")
shutil.move("hello.txt","../")


#文件的重命名
#os模块函数rename 可以对文件或者目录进行重命名
import os
li = os.listdir(".")
print li

if "hello.txt" in li:
    os.rename("hello.txt", "hi.txt")
elif "hi.txt" in li:
    os.rename("hi.txt","hello.txt")



#修改文件的后缀名 , 将后缀名文件html 修改成为htm
import  os
files = os.listdir(".")
for filename in files:
    pos = filename.find(".")
    if filename[pos+1:] =="html":
        newname = filename[:pos+1]+"htm"
        os.rename(filename,newname)

文件内容的查找和替换

    从 hello.txt  文件中查找字符串,  统计hello 出现的次数
    
#文件的查找
import re

f1 = file("hello.txt","r")
count =0
for s in f1.readlines():
    li = re.findall("hello",s)
    if len(li)>0:
        count =count+li.count("hello")
print "查找到"+str(count)+"个hello"
f1.close()

# 将hello.txt  中的字符串hello 全部替换为 hi 并把结果保存到 hello2.txt 中

f1 = file("hello.txt", "r")
f2 = file("hello2.txt", "w")
for s in f1.readlines():
    f2.write(s.replace("hello","hi"))
f1.close()
f2.close()


# 文件的比较, python
# 提供了difflib 用于对序列文件的比较,
# 如果要比较连个文件, 列出两个文件的一同, 就可以使用difflib 模块的
# SequenceMatcher 类来实现, 其中get_opcodes 可以返回两个序列的比较结果,
# 调用get_opcodes 之前, 需要生成1个 SequenceMatcher 对象

import difflib

f1 = file("hello.txt", "r")
f2 = file("hi.txt", "r")
src= f1.read()
dst =f2.read()

print src
print dst

s = difflib.SequenceMatcher(lambda x:x=="",src,dst)
for tag ,i1,i2,j1,j2 in s.get_opcodes():
    print ("%s src[%d:%d]=%s det[%d:%d=%s "\
           "tag,i1,i2,src[i1:i2],j1,j2,des[j1:j2]")



0 0