# 创建文件
context = '''信息技术! hello world'''
f = open('hello.txt', 'w') # 打开文件
f.write(context) # 把字符串写入文件
f.close() # 关闭文件
# 使用readline()读文件
f = open("hello.txt")
while True:
line = f.readline()
if line:
print (line)
else:
break
f.close()
# 使用readlines()读文件
f = open('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()
f = open("hello.txt")
context = f.read(5) # 读取文件前5个字节内容
print (context)
print (f.tell()) # 返回文件对象当前指针位置
context = f.read(5) # 继续读取5个字节内容
print (context)
print (f.tell()) # 输出文件当前指针位置
f.close()
# 使用writelines()写文件
f = open("hello.txt", "w+")
li = ["hello world\n", "hello China\n"]
f.writelines(li)
f.close()
# 追加新的内容到文件
f = open("hello.txt", "a+") # 写入方式为追加a+
new_context = "goodbye"
f.write(new_context)
f.close()
import os
open("hello.txt", "w")
if os.path.exists("hello.txt"):
os.remove("hello.txt")
# shutil模块实现文件的复制
import shutil
shutil.copyfile("hello.txt","hello2.txt")
shutil.move("hello.txt","../")
shutil.move("hello2.txt","hello3.txt")
# 修改文件名
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")
# 修改后缀名
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)
# 文件的查找
import re
f1 = open("hello3.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()
# 文件的替换
f1 = open("hello3.txt", "r")
f2 = open("hello2.txt", "w")
for s in f1.readlines():
f2.write(s.replace("hello", "hi"))
f1.close()
f2.close()
import difflib
f1 = open("hello3.txt", "r")
f2 = open("hello2.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]))
# 读配置文件
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 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"D:\developer\python\example\07"
VisitDir(path)
# 文件输入流
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")
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"D:\HXpython\07py"
showFileProperties(path)