【脚本语言系列】关于Python基础知识文件操作,你需要知道的事

如何进行文件操作

文件的创建、读写和修改

# -*- coding: utf-8 -*-
# create the file
context = '''hello world
hello MoseAaron
'''
f = file("hello.txt", 'w')
f.write(context)
f.close()
# -*- coding: utf-8 -*-
# read the file
f = open("hello.txt")
while True:
    line = f.readline()
    if line:
        print line,
    else:
        break
f.close()
hello world
hello MoseAaron
# -*- coding: utf-8 -*-
# read the file
f = open("hello.txt")
lines = f.readlines()
for line in lines:
    print line
hello world

hello MoseAaron
# -*- coding: utf-8 -*-
# read the file
f = open("hello.txt")
context = f.read()
print context
hello world
hello MoseAaron
# -*- coding: utf-8 -*-
# read the file
f = open("hello.txt")
context = f.read(5)
print context
print f.tell()
context = f.read(5)
print context
print f.tell()
f.close()
hello
5
 worl
10
# -*- coding: utf-8 -*-
# write the file
f = file("hello.txt", "w+")
li = ["hello world\n", "hello MoseAaron\n"]
f.writelines(li)
f.close()
# -*- coding: utf-8 -*-
# write the file
f = file("hello.txt", "a+")
new_context = "goodbye"
f.write(new_context)
f.close()

文件的拷贝、删除和重命名

# -*- coding: utf-8 -*-
# copy the file
src = file("hello.txt", "r")
dst = file("hello1.txt", "w")
dst.write(src.read())
src.close()
dst.close()
# -*- coding: utf-8 -*-
import shutil
# copy the file
shutil.copyfile("hello.txt", "temp.txt")
#shutil.move("hello.txt", "../")
shutil.move("temp.txt", "hello3.txt")
# -*- coding: utf-8 -*-
import os
# remove the file
file("hello2.txt","w")
if os.path.exists("hello2.txt"):
    os.remove("hello2.txt")
# -*- coding: utf-8 -*-
import os
# rename the file
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")
['.ipynb_checkpoints', 'hello1.txt', 'hello3.txt', 'hi.txt', 'Image 1.png', 'Image 2.png']
# -*- coding: utf-8 -*-
import os
# rename the file
files = os.listdir(".")
for filename in files:
    pos = filename.find(".")
    if filename[pos+1:] == "html":
        newname = filename[:pos+1]+"html"
        os.rename(filename, newname)
# -*- coding: utf-8 -*-
import os
# rename the file
files = os.listdir(".")
for filename in files:
    li = os.path.splitext(filename)
    if li[1] == ".html":
        newname = li[0] + ".htm"
        os.rename(filename, newname)
# -*- coding: utf-8 -*-
import glob
# rename the file
files = glob.glob("d:\\w*\\*.txt")
for filename in files:
    li = os.path.splitext(filename)
    if li[1] == ".html":
        newname = li[0] + ".htm"
        os.rename(filename, newname)

文件内容的搜索和替换

# -*- coding: utf-8 -*-
import re
# find in the file
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 "Find "+str(count) + " hello"
f1.close()
Find 2 hello
# -*- coding: utf-8 -*-
import re
# replace in the file
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()

文件的比较

# -*- coding: utf-8 -*-
import difflib
# compare the file
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 dst[%d:%d]=%s" %(tag, i1, i2, src[i1:i2], j1, j2, dst[j1:j2])
hello world
hi world
equal src[0:1]=h dst[0:1]=h
replace src[1:5]=ello dst[1:2]=i
equal src[5:11]= world dst[2:8]= world

配置文件的读写

# -*- coding: utf-8 -*-
import ConfigParser
# read the .ini file
config = ConfigParser.ConfigParser()
config.read("ODBC.ini")
sections = config.sections()
print "config section:", sections
o = config.options("ODBC 32 bit Data Sources")
print "config items:", o
v = config.items("ODBC 32 bit Data Sources")
print "content: ", v
# access the options and items
access = config.get("ODBC 32 bit Data Sources", "MS Access Database")
print access
excel = config.get("ODBC 32 bit Data Sources", "Excel Files")
print excel
dBASE = config.get("ODBC 32 bit Data Sources", "dBASE Files")
print dBASE
config section: ['ODBC 32 bit Data Sources', 'MS Access Database', 'Excel Files', 'dBASE Files']
config items: ['ms access database', 'excel files', 'dbase files']
content:  [('ms access database', 'Microsoft Access Driver(*.mdb)(32 \xce\xbb)'), ('excel files', 'Microsoft Excel Driver(*.xls)(32 \xce\xbb)'), ('dbase files', 'Microsoft dBase Driver(*.dbf)(32 \xce\xbb)')]
Microsoft Access Driver(*.mdb)(32 λ)
Microsoft Excel Driver(*.xls)(32 λ)
Microsoft dBase Driver(*.dbf)(32 λ)
# -*- coding: utf-8 -*-
import ConfigParser
# write the .ini file
config = ConfigParser.ConfigParser()
config.add_section("ODBC Driver Count")
config.set("ODBC Driver Count", "count", 2)
f = open("ODBC.ini", "a+")
config.write(f)
f.close()
# -*- coding: utf-8 -*-
import ConfigParser
# write the .ini file
config = ConfigParser.ConfigParser()
config.read("ODBC.ini")
config.set("ODBC Driver Count", "count", 3)
f = open("ODBC.ini", "r+")
config.write(f)
f.close()
# -*- coding: utf-8 -*-
import ConfigParser
# remove items in the .ini file
config = ConfigParser.ConfigParser()
config.read("ODBC.ini")
config.remove_option("ODBC Driver Count", "count")
config.remove_section("ODBC Driver Count")
f = open("ODBC.ini", "w+")
config.write(f)
f.close()

目录的创建和遍历

# -*- coding: utf-8 -*-
import os
# create the directory
os.mkdir("hello")
os.rmdir("hello")
os.makedirs("hello/world")
os.removedirs("hello/world")
# -*- coding: utf-8 -*-
import os,os.path
# walk the directory
def ListDir(path):
    li = os.listdir(path)
    for p in li:
        pathname = os.path.join(path, p)
        if not os.path.isfile(pathname):
            ListDir(pathname)
        else:
            print pathname
if __name__=="__main__":
    path = r".";
    ListDir(path)
.\hello.txt
.\hello1.txt
.\hello2.txt
.\hello3.txt
.\hi.txt
.\Image 1.png
.\Image 2.png
.\ODBC.ini
# -*- coding: utf-8 -*-
import os,os.path
# walk the directory
def ListDir(arg, dirname, names):
    for filepath in names:
        print os.path.join(dirname, filepath)
if __name__=="__main__":
    path = r".";
    os.path.walk(path, ListDir, ())
.\.ipynb_checkpoints
.\hello.txt
.\hello1.txt
.\hello2.txt
.\hello3.txt
.\hi.txt
.\Image 1.png
.\Image 2.png
.\ODBC.ini
# -*- coding: utf-8 -*-
import os
# walk the directory
def ListDir(path):
    for root,dirs,files in os.walk(path):
        for filepath in files:
            print os.path.join(root, filepath)

if __name__=="__main__":
    path = r".";
    ListDir(path)
.\hello.txt
.\hello1.txt
.\hello2.txt
.\hello3.txt
.\hi.txt
.\Image 1.png
.\Image 2.png
.\ODBC.ini

文件和流

# -*- coding: utf-8 -*-
import sys
# standard input
sys.stdin = open("hello.txt", "r")
for line in sys.stdin.readlines():
    print line
hello world
# -*- coding: utf-8 -*-
import sys
# standard output
sys.stdout = open(r"./hello.txt", "a")
print "goodbye"
sys.stdout.close()
# -*- coding: utf-8 -*-
import sys,time
# standard error
sys.stderr = open("record.log", "a")
f = open(r"hello.txt","r")
t = time.strftime("%Y-%m-%d%X", time.localtime())
context = f.read()
if context:
    sys.stderr.write(t+" "+context)
else:
    raise Exception, t+"exceptin information"
# -*- coding: utf-8 -*-
# file input stream
def FileInputStream(filename):
    try:
        f = open(filename)
        for line in f:
            for byte in line:
                yield byte
    except StopIteration, e:
        f.close()
        return
# file output stream
def FileOutputStream(inputStream, filename):
    try:
        f = open(filename,"w")
        while True:
            byte = inputStream.next()
            f.write(byte)
    except StopIteration, e:
        f.close()
        return

if __name__ == "__main__":
    FileOutputStream(FileInputStream("hello.txt"),"hello2.txt")
# -*- coding: utf-8 -*-
import time, os
# show the properties of files
def ShowFileProperties(path):
    for root, dirs, files in os.walk(path, True):
        print "location:"+root
        for filename in files:
            state = os.stat(os.path.join(root, filename))
            info = "file name:" + filename+ " "
            info = info +"size:"+("% d "% state[-4]) + ""
            t = time.strftime("%Y-%m-%d%X", time.localtime(state[-1]))
            info = info +"created time:"+ t + ""
            t = time.strftime("%Y-%m-%d%X", time.localtime(state[-2]))
            info = info +"last modified time:"+ t + ""
            t = time.strftime("%Y-%m-%d%X", time.localtime(state[-3]))
            info = info +"last access time:"+ t + ""
            print info
if __name__ == "__main__":
    path = r"."
    ShowFileProperties(path)
location:.
file name:hello.txt size: 13 created time:2017-06-0909:23:37last modified time:2017-06-0912:12:04last access time:2017-06-0909:23:37
file name:hello1.txt size: 37 created time:2017-06-0909:48:39last modified time:2017-06-0909:48:39last access time:2017-06-0909:48:39
file name:hello2.txt size: 13 created time:2017-06-0910:41:50last modified time:2017-06-0912:41:12last access time:2017-06-0910:41:50
file name:hello3.txt size: 37 created time:2017-06-0909:53:41last modified time:2017-06-0909:53:41last access time:2017-06-0909:53:41
file name:hi.txt size: 8 created time:2017-06-0910:45:43last modified time:2017-06-0910:49:23last access time:2017-06-0910:45:43
file name:Image 1.png size: 8185 created time:2017-06-0716:23:55last modified time:2017-06-0716:23:55last access time:2017-06-0716:23:55
file name:Image 2.png size: 8185 created time:2017-06-0716:29:56last modified time:2017-06-0716:29:56last access time:2017-06-0716:29:56
file name:ODBC.ini size: 387 created time:2017-06-0911:04:07last modified time:2017-06-0911:14:30last access time:2017-06-0911:04:08
file name:record.log size: 64 created time:2017-06-0912:12:17last modified time:2017-06-0912:38:39last access time:2017-06-0912:12:17 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值