文件对象
反斜杠在python字符串中是一个特殊字符,需要转义:使用两个反斜杠 或在路径前加r
"C:\Windows\Temp" r"C:windowsTemp"
1 编写文本文件
file对象代表对一个文件的连接,而不是文件本身,如果试图打开或者向一个不存在的文件写数据,python将自动创建该文件。如果文件存在,会删除它并创建一个新文件。
def make_text_file():
a=open('E://test.txt',"w") "w" 参数:向文件中写数据,如果没有指定参数,则从文件中读数据,若文件不存在,将抛出异常。
a.write("this is how you create a new text file")
a.close()
import os
def make_another_file():
if os.path.isfile('E://test.txt'): 检查文件是否已经存在
print("you are trying to create a file that already exists!")
else:
f=open('E://text.txt',"w")
f.write("2 this is how you create a new text file")
f.close()
打开一个文件时可以指定一个相对路径(相对于当前目录的路径,当前目录是指程序 或者 python正在运行的地方)或者一个绝对路径
2 向文件中追加文本
追加参数"a",这样可以保证文件中已有的数据不被重写,而是将新文本追加到文件末尾
def add_some_text():
if os.path.isfile('E://test.txt'):
a=open('E://test.txt',"a")
a.write("here is some additional text!")
a.close()
else:
print("there is no file")
write函数不会自动写换行符,任何时候想向文件中增加换行符时,必须使用转义序列 空格也一样。如果不自己添加空格、制表符、换行符,下一次向文件中添加的文本会紧跟在已有文本之后
添加多行文本:
def even_more_text():
if os.path.isfile("E://test.txt"):
a=open("E://test.txt","a")
a.write("""
here is
more
text""")
a.close()
else:
print("there is no file")
3 读文本文件
a.open('','r') 如果文件不存在,将抛出一个异常
可以使用 readline方法从文件中读出一行文本,返回的字符串末尾是换行符。若要逐行读取文件内容,可重复调用readline方法。
read方法一次性地读取文件中的剩余内容,该方法返回文件中未读取的所有内容
def read_txt():
if os.path.isfile("E://test.txt"):
a=open("E://test.txt","r")
txt=a.read()
a.close()
print(txt)
else:
print("there is no this file")
打印每一行的长度:
def print_line_len():
if os.path.isfile("E://test.txt"):
a=open("E://test.txt","r")
text=a.readlines()
for line in text:
print (len(line))
else:
print("there is no the file")
每一行都包含换行符,因此看起来为空的行的长度为1
4 文件异常
当python在执行文件操作并遇到问题时,它将抛出一个IOError异常:
试图打开读取一个不存在的文件
试图在一个不存在的目录中创建文件
试图打开一个没有读访问权限的文件
试图在一个没有写访问权限的目录下创建文件
计算机遇到磁盘错误 或者网络错误
5 路径目录
windows使用反斜杠将一个路径中的目录名称分隔开,而linux/unix 使用正斜杠。windows使用驱动器名称,而其他系统则不用。
python 将路径和目录操作隐藏在os模块中,方便使用。但使用os并不能解决所有移植问题,os模块中的一些函数并不是在所有平台上都可用。
6 os中的异常
os模块中的函数在失败时会抛出OSError异常。异常的字符串表示描述了遇到的问题
7 路径
os.path提供了操作路径的函数。由于路径也是字符串,可以使用普通的字符串操作方法组合和分解文件路径。
使用os.path操作路径,可使程序易于移植。且可以处理一此特殊情形。
1 使用 os.path.join可将目录名称组合成路径。python使用适合操作系统的路径分隔符
>>> import os
>>> os.path.join("snakes","python")
'snakes\python'
2 函数os.path.split具有相反的功能,它将路径的最后一个组件提取出来。返回包含两个项的元组:父目录的路径以及最后一个路径组件。
使用自动分解序列获取split返回的元组数据
>>> parent_path,name=os.path.split("E:\workswin6.4")
>>> print(parent_path)
E:works
>>> print(name)
win6.4
使用递归完成分解路径
>>> ("test1",)+("test2",)
('test1', 'test2')
def split_fully(path):
parent_path,name=os.path.split(path)
if name=="":
return(parent_path,)
else:
return split_fully(parent_path)+(name,)
>>> split_fully("E:\workswin6.4")
('E:\', 'works', 'win6.4')
编写递归函数时,要确保字不会无限次地调用自身。单个元素的元组,必须在圆括号中包含一个逗号。
3 可以使用os.path.splitext分解出扩展名
>>> os.path.splitext("image.jpg")
('image', '.jpg')
>>> part1,part2=os.path.splitext("image.jpg")
4 os.path.normpath 可以规范化 或 清理 路径
>>> print(os.path.normpath(r"C:\program fielsperl..python37"))
C:program fielspython37
5 os.path.abspath 将一个相对路径转变为一个绝对路径
>>> print(os.path.abspath("test.txt"))
E:pythonscript est.txt
输出取决于调用abspath时的当前路径。不检查目录存在
6 os.path.exists 判断某个路径是否实际存在。它仅简单的返回true false
>>> os.path.exists("C:\test.txt")
False
8 目录内容 找出硬盘上实际存在哪些内容
1 获取目录的内容
os.listdir("E:\works")
返回结果是目录条目的名称,不是完整路径。如果需要某个条目的完整路径,必须使用 os.path.join构造。
结果中既有文件名称也有目录名称,从os.listdir的结果中无法区分两都
结果中不包含 "." ".."这两个代表当前目录和其父目录的特殊目录名称
>>> os.listdir(".") 返回当前目录下的条目名称
def print_dir(dir_path):
for name in os.listdir(dir_path):
print(os.path.join(dir_path,name))
>>> print_dir(".")
.ch5.py
os.listdir返回的条目顺序是任意的,可以使用 sorted 函数排序,默认得到的结果按字母表排序,并区分大小写
>>> sorted(os.listdir("."))
2 获取文件信息
如果是文件 则os.path.isfile 返回True;如果指向目录则os.path.isdir返回True,如果路径不存在,都返回:False
3 递归目录列表
def print_tree(dir_path):
for name in os.listdir(dir_path):
full_path=os.path.join(dir_path,name)
print(full_path)
if os.path.isdir(full_path):
print_tree(full_path)
os.path.getsize 在不必打开和扫描某个文件的情况下以字节为单位返回该文件的大小。
os.path.getmtime返回从1970年起到文件上次被修改的时间之间的秒数,需要使用 time.ctime换为易于理解的形式
>>> os.path.getsize("E:\1.jpg")
210413
>>> os.path.getmtime("E:\1.jpg")
1542848624.8716433
>>> import time
>>> mod_time=os.path.getmtime("E:\1.jpg")
>>> print(time.ctime(mod_time))
Thu Nov 22 09:03:44 2018
def print_dir_info(dir_path):
for name in os.listdir(dir_path):
full_path=os.path.join(dir_path,name)
if os.path.isfile(full_path):
file_size=os.path.getsize(full_path)
mod_time=time.ctime(os.path.getmtime(full_path))
print("%-32s:%8d bytes,modified %s"%(name,file_size,mod_time))
9 重命名、移动、复制、删除文件
1 模块shutil中包含了操作文件的函数。可以使用函数shutil.move重命名一个文件:
>>> import shutil
>>> shutil.move("E:\test.txt","E:\test.txt.backup")
或者可以使用它将一个文件移动到另外一个目录下:
>>> shutil.move("E:\test.txt.backup","E:\works\")
'E:\works\test.txt.backup'
os 也包含一个可以重命名和移动文件的函数 os.rename,这个可能不能指定一个目录名称作为目标,在某些系统上,不能将一个文件移动到另外一个磁盘或者文件系统中。 一般应当使用 shutil.move
shutil.copy 将一个文件复制为具有一个新名称的文件,或者复制到一个新目录下。
>>> import shutil
>>> shutil.copy("E:\works\test.txt.backup","E:\test.txt")
'E:\test.txt'
2 删除文件调用 os.remove即可,或 os.unlink
3 文件权限 在不同的 平台上的工作方式不同。需要改变一个文件或目录的权限,可以使用 os.chmod函数
10 轮换文件
老版本有一个数字后缀,当前版本没有。必须确保首选要重命名老版本。如修改日志版本
def make_version_path(path,version):
if version==0:
#no suffix for version 0 ,the current version.
return path
else:
#append a suffix to indicate the older version.
return path+"."+str(version)
def rotate(path,version=0):
#construct the name of the version we are rotating.
old_path=make_version_path(path,version)
if not os.path.exists(old_path):
#it doesn't exist,so complain.
raise IOError("'%s' doesn't exist" %path)
#construct the new version name for this file.
new_path=make_version_path(path,version+1)
# is there already a version with this name?
if os.path.exists(new_path):
#yes rotate it out of th way first!
rotate(path,version+1)
# now we can rename the version safely!
shutil.move(old_path,new_path)
def rotate_log_file(path):
if not os.path.exists(path):
# the file is missing, so create is.
new_file=open(path,"w")
#close the new file immediately,which leaves it empty.
del new_file
# now rotate it
rotate(path)
10 创建和删除目录
os.mkdir 实现创建一个空目录 >>> os.mkdir("E:\pythonscript\txt")
os.makedirs 在不存在父目录时创建父目录:>>> os.makedirs("E:\photo\image")
os.rmdir删除目录 该函数仅对空目录有效,如果要删除的目录不为空,首产需要删除该目录的内容。
>>> os.rmdir("E:\photo\image") 仅删除子目录 image
shutil.rmtree可以在目录包含其他文件和子目录的情况下将该目录删除
>>> shutil.rmtree("E:\photo") 删除父目录及子目录文件
11 通配
通配符是一些特殊字符,例如:* 和?
python在模块glob中提供了名称也为glob的函数,实现了对目录内容进行通配功能。glob.glob函数接受模式作为输入,并返回所有匹配的文件名和路径名列表。与os.listdir类似。
在windows操作系统下模式 M*可以匹配名称以m和M开头的所有文件,因为文件名称和文件名称通配是不区分大小写的。在大多数其他操作系统上 ,通配是区分大小写的。
>>> import glob
>>> glob.glob("C:\Program Files\M*")
>>> glob.glob("E:\*.*")
只返回指定目录下的名称 与os.listdir不同
* 0个或多个任意字符
?任意单个字符
[...]方括号中列出的任意一个字符
[!...]不在方括号中出现的任意一个字符
也可以在方括号之间使用某个范围内的字符,[m-p] 匹配m/n/o/p 中的任意一个字母
[!1-9]匹配数字以外的任意字符
通配是为文件操作选择一组相似文件的较为便捷的方法。
>>> for path in glob.glob("C:\*.bak"):
os.remove(path)
>>> for path in glob.glob("D:\*\*\*.bak"):
os.remove(path)
小结:
使用file对象可以向文件中写字符串,并且一次性地或逐行读取文件中的内容。
使用 os.listdir /glob 可以列出磁盘上的内容
文件对象代表了对一个文件的链接,而不是文件本身,但是如果以写方式打开一个并不存在的文件,python会自动创建该文件。
使用append方法而不是write方法,可向文件中追加内容,这确保文件中的数据不被重写
使用参数 r 从文件中读数据
readline方法返回文件中的第一行文件
当结束读文件时,确保要显式地关闭该文件,并删除文件对象。
模块os中的os.path子模块提供了操作路径的函数
模块os.listdir可以列出一个目录下的文件、子目录等内容
通配 是黑客的行话,用来表示展开文件名称模式中 通配符。python在模块glob中提供了同名函数glob,它实现了对目录内容的通配操作。glob.glob接受glob模式作为输入,并返回匹配的文件名或踒名称列表。
列出所有子目录、文件 按字母顺序排序
def print_dir(path):
pathlist=[]
filelist=[]
for p in os.listdir(path):
fullpath=os.path.join(path,p)
if os.path.isfile(fullpath):
filelist.append(fullpath)
else:
pathlist.append(fullpath)
print(sorted(pathlist))
print(sorted(filelist))