1.1 创建文件
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 创建文件
context = '''hello world
hello China
'''
f = file('hello.txt', 'w') # 打开文件
f.write(context) # 把字符串写入文件
f.close() # 关闭文件
输出:
当前目录下创建txt文件,并写入context内容
1.2 读取文件
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 使用readline()读文件
f = open("hello.txt")
while True:
line = f.readline()
if line: #当前行不为空
print line,
else:
break
f.close()
# 使用readlines()读文件
f = file('hello.txt')
lines = f.readlines()
for line in lines:
print line,
f.close() # 关闭文件
# 使用read()读文件
f = open("hello.txt")
context = f.read()
print context
f.close()
# read(size)
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 world
hello China
hello world
hello China
hello world
hello China
hello
5
worl #有一空格
10
>>>
1.3 文件写入内容
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 使用writelines()读文件
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()
输出:
新建hello.txt",再写入
hello world
hello China
goodbye
1.4 文件删除
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import os
file("hello.txt", "w")
if os.path.exists("hello.txt"):
os.remove("hello.txt")
1.5 文件复制
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 使用read()、write()实现拷贝
# 创建文件hello.txt
src = file("hello.txt", "w")
li = ["hello world\n", "hello China\n"]
src.writelines(li)
src.close()
# 把hello.txt拷贝到hello2.txt
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","hello2.txt") 拷贝内容到2中
shutil.move("hello.txt","../") 移动到上级目录
shutil.move("hello2.txt","hello3.txt") 2的内容拷贝到3,并将2删除,3原来的内容被清空
1.6 文件重命名/后缀名
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 修改文件名
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")
>>>
['alter_extension.py', 'hello.html', 'hi.html', 'hi.txt', 'rename_file.py']
>>>
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 修改后缀名1
import os
li = os.listdir(".") #读取并输出当前目录
print li
files = os.listdir(".")
for filename in files:
pos = filename.find(".")
if filename[pos + 1:] == "html":
newname = filename[:pos + 1] + "htm"
os.rename(filename,newname)
li = os.listdir(".") #读取并输出当前目录
print li
# 修改后缀名2
import os
files = os.listdir(".")
for filename in files:
li = os.path.splitext(filename)
if li[1] == ".html":
newname = li[0] + ".htm"
os.rename(filename,newname)
li = os.listdir(".") #读取并输出当前目录
print li
>>>
['alter_extension.py', 'hello.html', 'hello.txt', 'hi.html', 'rename_file.py']
['alter_extension.py', 'hello.htm', 'hello.txt', 'hi.htm', 'rename_file.py']
['alter_extension.py', 'hello.htm', 'hello.txt', 'hi.htm', 'rename_file.py']
>>>
1.7 文件内容查找与替换
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import re
# 文件的查找
f1 = file("hello.txt", "r")
count = 0
for s in f1.readlines():
li = re.findall("hello", s) 寻找hello
if len(li) > 0:
count = count + li.count("hello") 累加
print "查找到" + str(count) + "个hello"
f1.close()
# 文件的替换
f1 = file("hello.txt", "r")
f2 = file("hello3.txt", "w")
for s in f1.readlines(): 遍历
f2.write(s.replace("hello", "hi")) 将f1中的hello替换为hi后再写入到f2中
f1.close()
f2.close()
>>>
查找到3个hello
>>>
1.8 文件比较
#!/usr/bin/python
# -*- coding: UTF-8 -*-
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 dst[%d:%d]=%s" % \ 输出不同处
(tag, i1, i2, src[i1:i2], j1, j2, dst[j1:j2]))
>>>
hello world
hi hello
insert src[0:0]= dst[0:3]=hi
equal src[0:5]=hello dst[3:8]=hello
replace src[5:11]= world dst[8:11]=
>>>
1.9 配置文件访问
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 读配置文件
import ConfigParser
config = ConfigParser.ConfigParser()
config.read("ODBC.ini")
sections = config.sections() # 返回所有的配置块
print "配置块:", sections
o = config.options("ODBC 32 bit Data Sources") # 返回所有的配置项
print "配置项:", o
v = config.items("ODBC 32 bit Data Sources")
print "内容:", v
# 根据配置块和配置项返回内容
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
# 写配置文件
import ConfigParser
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()
# 修改配置文件
import ConfigParser
config = ConfigParser.ConfigParser()
config.read("ODBC.ini")
config.set("ODBC Driver Count", "count", 3)
f = open("ODBC.ini", "r+")
config.write(f)
f.close()
# 删除配置文件
import ConfigParser
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()
>>>
配置块: ['ODBC 32 bit Data Sources', 'MS Access Database', 'dBASE Files', 'Excel Files']
配置项: ['ms access database', 'dbase files', 'excel files']
内容: [('ms access database', 'Microsoft Access Driver (*.mdb) (32 \xce\xbb)'), ('dbase files', 'Microsoft dBase Driver (*.dbf) (32 \xce\xbb)'), ('excel files', 'Microsoft Excel Driver (*.xls) (32 \xce\xbb)')]
Microsoft Access Driver (*.mdb) (32 位)
Microsoft Excel Driver (*.xls) (32 位)
Microsoft dBase Driver (*.dbf) (32 位)
>>>
1.10 目录创建与删除
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import os
os.mkdir("hello") 创建
#os.rmdir("hello") 删除
os.makedirs("hello/world") 多级目录
#os.removedirs("hello/world")
1.11 遍历目录
# 递归遍历目录
import os
def VisitDir(path):
li = os.listdir(path)
for p in li:
pathname = os.path.join(path, p)
if not os.path.isfile(pathname):
VisitDir(pathname)
else:
print pathname
if __name__ == "__main__":
path = r"E:\study\python\python example\07\"
VisitDir(path)
>>>
E:\study\python\python example\07\7.1.1\create_file.py
E:\study\python\python example\07\7.1.1\hello.txt
E:\study\python\python example\07\7.1.2\hello.rar
E:\study\python\python example\07\7.1.2\hello.txt
E:\study\python\python example\07\7.1.2\read_file.py
E:\study\python\python example\07\7.1.2\read_file2.py
E:\study\python\python example\07\7.1.2\z.zip
E:\study\python\python example\07\7.1.3\hello.txt
E:\study\python\python example\07\7.1.3\write_file.py
E:\study\python\python example\07\7.1.4\delete_file.py
E:\study\python\python example\07\7.1.5\copy_file.py
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# os.path.walk遍历目录
import os,os.path
def VisitDir(arg, dirname, names):
for filepath in names: 遍历目录
print os.path.join(dirname, filepath) 输出路径及文件名
if __name__=="__main__":
path = r"E:\study\python\python example\07\7.2.2"
os.path.walk(path, VisitDir, ())
>>>
E:\study\python\python example\07\7.2.2\os_path_walk.py
E:\study\python\python example\07\7.2.2\os_walk.py
E:\study\python\python example\07\7.2.2\visitdir.py
>>>
# -*- coding: UTF-8 -*-
# os.walk遍历目录
import os
def VisitDir(path):
for root,dirs,files in os.walk(path,True):
for filepath in files:
print os.path.join(root, filepath)
if __name__=="__main__":
path = r"E:\study\python\python example\07\7.2.2"
VisitDir(path)
>>>
E:\study\python\python example\07\7.2.2\os_path_walk.py
E:\study\python\python example\07\7.2.2\os_walk.py
E:\study\python\python example\07\7.2.2\visitdir.py
>>>
1.12 定向输出
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 重定向输出
import sys
sys.stdout = open(r"./hello.txt","a")
print "goodbye" hello文件中追加了goodbye字符
sys.stdout.close()
#输出到屏幕
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import sys
sys.stdin = open("hello.txt", "r")
for line in sys.stdin.readlines():
print line
>>>
hello worldgoodbye
>>>
#异常输出
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import sys,time
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 + " 异常信息"
实用:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 文件输入流
def FileInputStream(filename):
try:
f = open(filename)
for line in f:
for byte in line:
yield byte
except StopIteration, e:
f.close()
return
# 文件输出流
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")
#!/usr/bin/python
# -*- coding: UTF-8 -*-
def showFileProperties(path):
'''显示文件的属性。包括路径、大小、创建日期、最后修改时间,最后访问时间'''
import time,os
for root,dirs,files in os.walk(path,True):
print "位置:" + root
for filename in files:
state = os.stat(os.path.join(root, filename))
info = "文件名: " + filename + " "
info = info + "大小:" + ("%d" % state[-4]) + " "
t = time.strftime("%Y-%m-%d %X", time.localtime(state[-1]))
info = info + "创建时间:" + t + " "
t = time.strftime("%Y-%m-%d %X", time.localtime(state[-2]))
info = info + "最后修改时间:" + t + " "
t = time.strftime("%Y-%m-%d %X", time.localtime(state[-3]))
info = info + "最后访问时间:" + t + " "
print info
if __name__ == "__main__":
path = r"E:\study\python\python example\07"
showFileProperties(path)
>>>
浣嶇疆锛欵:\study\python\python example\07
文件名: hello.txt 大小:26 创建时间:2012-06-09 19:34:34 最后修改时间:2012-10-28 15:59:13 最后访问时间:2012-10-28 15:58:11
浣嶇疆锛欵:\study\python\python example\07\7.1.1
文件名: create_file.py 大小:267 创建时间:2012-06-09 19:34:34 最后修改时间:2012-10-28 15:33:40 最后访问时间:2012-06-09 19:34:34
文件名: hello.txt 大小:38 创建时间:2012-10-28 15:33:42 最后修改时间:2012-10-28 15:33:42 最后访问时间:2012-10-28 15:33:42
浣嶇疆锛欵:\study\python\python example\07\7.1.2
文件名: hello.rar 大小:106 创建时间:2012-06-09 19:34:34 最后修改时间:2008-02-24 13:57:10 最后访问时间:2012-06-09 19:34:34
本文来自博客园,作者:{Julius},转载请注明原文链接:https://www.cnblogs.com/bestechshare/p/16447863.html
可微信加我,了解更多,WeChat:{KingisOK}