您的位置:首页 > 编程语言 > Python开发

学习python的第四十五天-第七章 使用python处理文件

2016-12-27 14:51 531 查看

第七章 使用
python
处理文件

数据的储存可以使用数据库,也可以使用文件。数据库的使用保持了数据的完整性和关联性,而且使数据更安全。使用文件储存数据则非常方便,不必安装数据库管理系统等运行环境。文件通常用于存储应用软件的参数或临时性数据。
python
提供了
os
os.path
等模块处理文件。

7.1 文件的常见操作

文件通常用于储存数据或应用系统的参数。
python
提供了包括打开文件,读写文件,复制和删除文件等函数。

文件的打开或创建可以使用函数
open()
。该函数可以指定处理模式,设置打开的文件为只读,只写或读写状态。
file
类用于文件管理,可以对文件进行创创建,打开,读写,关闭等操作。文件的处理一般分为三个步骤:

创建并打开文件

调用
file
对象的
read()
write()
等方法处理文件

调用
close()
关闭文件,释放
file
对象占用的资源

close()
方法是必要的,虽然
python
提供了垃圾回收机制,清理不再使用的对象,但是手动释放不需要的资源是一种良好的习惯。同时也主动告诉
python
的垃圾回收器,该对象需要被清除。

这段代码演示了文件的创建,写入和关闭操作。

# 创建文件
context = '''hello world'''

f = open('hello.txt', 'w')          # 打开文件
f.write(context)                # 把字符串写入文件
f.close()                       # 关闭文件


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

readline()
每次读取文件中的一行,需要使用永真表达式(
while True:
)循环读取文件。但当文件指针移动到文件末尾时,依然使用
readline()
读取文件将会出现错误。所以在程序中需要加入一个判断句,判断指针是否移到了文件的尾部,并作出判断。

# 使用readline()读文件
f = open("hello.txt")
while True:
line = f.readline()
if line:
print (line)
else:
break
f.close()


使用
readlines()
读取文件,需要通过循环访问
readlines()
返回列表中的元素。函数
readlines()
可以一次性读取文件中的多行数据。

# 使用readlines()读文件
f = file('hello.txt')
lines = f.readlines()
for line in lines:              # 一次读取多行内容
print (line)
f.close()


第3行代码调用
readlines()
,把文件
hello.txt
中所有的内容存储在列表
lines
中。

读取文件最简单的方法是使用
read()
read()
将从文件中一次性读出所有内容,并赋值给1个字符串变量。

# 使用read()读文件
f = open("hello.txt")
context = f.read()
print (context)
f.close()


可以通过控制
read()
参数的值,返回指定字节的内容。

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()


文件的写入有多种方法,可以使用
write()
writelines()
方法。

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


如果需要保留文件中原有的内容,只是追加新的内容,可以使用模式“
a+
”打开文件。使用
writelines()
写文件的速度更快,如果需要写入的文件字符串非常多,可以使用
writelines()
提高效率。

文件的删除需要使用
os
模块和
os.path
模块。
os
模块提供了对系统环境,文件,目录等操作系统级的接口函数。文件的删除需要调用
remove()
函数实现,要删除文件之前需要判断文件是否存在,若存在则删除文件,否则不进行任何操作。

file
类并没有提供直接复制文件的办法,但是可以使用
read()
write()
方法,同样可以实现复制文件的功能。

# 使用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 = open("hello.txt", "r") #只读模式打开
dst = open("hello2.txt", "w") #写入模式打开
dst.write(src.read()) #dst写入读取src的内容
src.close()
dst.close()


os
模块的函数
rename()
可以对文件或目录进行重命名。下面这段代码实现的是如果当前目录存在名为
hello.txt
文件,则重命名为
hi.txt
,如果存在
hi.txt
文件,就重命名为
hello.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")


其中第3行代码调用了
listdir()
返回当前目录的文件列表,“
.
”表示当前目录。

在实际应用中,需要把某一类文件修改为另外一种类型,也就是修改文件的后缀名,这种需求可以通过函数
rename()
和字符串查找的函数实现。

# 修改后缀名
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)


pos + 1
表示“
.
”后的位置,
filename[:pos + 1]
表示从
filename
的开头位置到“
.
”这段分片。

7.1 目录的常见操作

目录的创建和删除可以使用
mkdir()
makedirs()
rmdir()
removedirs()
实现。

import os

os.mkdir("hello")
os.rmdir("hello")
os.makedirs("hello\world")
os.removedirs("hello\world")


第3行代码创建一个名为
“hello”
的目录;

第4行代码删除目录
“hello”


第5行代码创建多级目录,先创建目录
“hello”
,再创建子目录
“world”


第6行代码删除目录
“hello”
“world”


目录的遍历有两种实现方法,一种是递归函数,一种是
os.walk()
函数。

7.4 文件处理示例——文件属性浏览程序

我省略了 7.3 的学习,这部分是文件和流,因为这部分内容对我来说暂时有些难理解,所以先搁置一下。

7.4这部分是设计一个浏览文件属性的程序。通过给定的目录路径查看文件的名称,大小,创建时间,最后修改日期和最后访问时间。功能的实现大致分为三个步骤:

遍历
path
指定的目录,获取每个子目录的路径;

遍历子目录下的所有文件,并返回文件的属性列表;

分解属性列表,对属性列表的值进行格式化输出。

代码如下:

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)


这段代码暂时还没有搞明白,因为马上要期末考试了,
python
只能先放一放。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python 文件 目录