#!/usr/local/bin/python
#encoding:utf-8
'''
open(file,mode='r',buffering=-1,encoding=None,errors=None,newline=None,closefd=True,opener=None) -> file object
'''
#7.1.1 文件的创建
#注意win环境下路径应用/
# context = '''hello world'''
# f = open('./hello.txt','w')
# f.write(context)
# f.close()
#7.1.2 文件的读取
#1.按行读取 readline()
# readline()每次读取文件中的一行,当文件的指针移动到文件的末尾时,依然使用readline()读取文件将出现错误
# 使用readline()读取文件
# 如果把第4行改为line = f.readline(2)表示每行每次读取2个字节,直到行尾
# f= open('hello.txt','r')
# while True:
# line = f.readline()
# if line:
# print (line)
# else:
# break
# f.close()
#2.多行读取方式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','r')
# context = f.read()
# print(context)
# f.close()
# f = open('hello.txt','r')
# context = f.read(5) # 读取文件前5个字节的内容
# print(context)
# print(f.tell()) # 返回文件对象当前指针位置
# context = f.read(5) # 继续读取5个字节内容
# print(context)
# print(f.tell()) # 输出文件当前指针位置
# f.close()
# 7.1.3 文件的写入
# 使用writelines()写文件
# f = open('hello.txt', 'w+')
# li = ['hello world\n','hello china\n']
# f.writelines(li)
# f.close()
# 追加新的内容到文件
# f = open('hello.txt','a+')
# new_context = 'goodbye'
# f.write(new_context)
# f.close()
# 7.1.4 文件的删除
# import os
# #open('hello.txt', 'w')
# if os.path.exists('hello.txt'):
# os.remove('hello.txt')
# 7.1.5 文件的复制
# 使用read()、write()实现复制
# 创建文件hello.txt
# src = open('hello.txt','w')
# li = ['hello world\n','hello china\n']
# src.writelines(li)
# src.close()
# # 把hello.txt复制到hello2.txt
# src = open('hello.txt','r')
# dst = open('hello2.txt','w')
# dst.write(src.read())
# src.close()
# dst.close()
# shutil模块实现文件的复制
# import shutil
# shutil.copyfile('hello.txt','hello2.txt')
# Python 2.7中shutil.copyfile()方法dst路径必须包含完整文件名
# Python 3.X中可写作shutil.copyfile('hello.txt','../')
# shutil.copyfile('hello.txt','../hello.txt')
# shutil.copyfile('hello2.txt','hello3.txt')
# 7.1.6 文件的重命名
# 修改文件名
# 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 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)
# 7.1.7 文件内容的搜索和替换
# 文件的查找
# import re
#
# f1 = open('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()
# 文件的替换
# f1 = open('hello.txt','r')
# f2 = open('hello2.txt','w')
# for s in f1.readlines():
# f2.write(s.replace('hello','hi'))
# f1.close()
# f2.close()
# 7.3.1 Python的流对象
# 1. stdin
import sys
sys.stdin = open("hello.txt", "r")
for line in sys.stdin.readlines():
print(line)
# 2. stdout
import sys
sys.stdout = open(r"./hello.txt", "a")
print("goodbye")
sys.stdout.close()
# 3. stderr
import sys, time
sys.stdeff = 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 + " 异常信息"
#7.3.2 模拟Java的输入、输出流
# 文件输入流
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")
# 7.4 文件处理示例--文件属性浏览程序
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:\developer\python\example\07\7.2.2"
showFileProperties(path)