Python系列之 - python文件操作
来源:互联网 发布:武汉理工大学网络教学 编辑:程序博客网 时间:2024/06/05 15:01
python对于文件的操作提供了专门的函数,并提供了一系列方法来对文件进行读取、写入等操作,下面对文件操作的一些方法进行介绍
一、打开文件的方法
python 提供两种方法来打开文件: file 、open
1 file方式打开文件
openfile = os.path.dirname(os.path.abspath("__file__")) + "\\source.txt"f = file(openfile,'r')print(f.read())f.close()
2 open方式打开文件
openfile = os.path.dirname(os.path.abspath("__file__")) + "\\source.txt"f = open(openfile,'r')print(f.read())f.close()
你如果去查看open的方法你就会发现,其实open方法内部也是通过file方式来打开文件的,这两种方法其实是一样的. 但你有没有发现,每次打开文件后最后都需要执行以下close()方法来关闭文件,如果你在操作的过程中可能会忘了关闭文件而释放资源。那么我们可以通过下面的方式让python自动关闭释放文件,它就是with ....open
openfile = os.path.dirname(os.path.abspath("__file__")) + "\\source.txt"with open(openfile,'r') as f: print(f.read())
通过这种方法,当执行完with语句后系统将自动释放打开的文件。
注意:在3.x的版本中已经无法直接使用file来打开文件了,只能使用open方法
二 文件打开模式
对于open(filename,arg) 中文件打开模式arg参数有以下几种方式:
三 文件操作函数
文件读操作
1. read() 读取文件中的所有内容,返回结果为字符串<str>
openfile = os.path.dirname(os.path.abspath("__file__")) + "\\source.txt"with open(openfile, 'r') as f: a = f.read() print(type(a)) print(a)结果:<class 'str'>1234567890123
read也可以支持读取指定长度的内容,方法为 read(int)
int为读取的长度,这个值在python2. 与 python3.x中是有区别的。 在 python 3.x 中read()带参数是读取的为字符长度,而在pythoh2.x中读取的为字节数.我们来看下面的例子:
python 3.x:
# ttt.txt内容:你123abcda = open('ttt.txt', 'r', encoding='utf-8')print(a.tell()) # 结果:0print(a.read(3)) # 结果:你12print(a.tell()) # 结果:5
python 2.x:
# ttt.txt内容:你123abcda = open('ttt.txt', 'r')print(a.tell()) # 结果:0print(a.read(3)) # 结果:你print(a.tell()) # 结果:3
从以上的结果中我们很明显的看到,在2.x中和3.x中的read的方式是不一样的,刚开始tell()的结果都为0,我们知道一个中文字符占3个字节, 3.x 中是按字符读取,所以read(3)读取了3个字符,返回'你12‘,而在2.x中是按字节读取,所以只读取'你'.这是python升级之后的一个变化。但是也有个问题,虽然read意识到()方法做了改动,但是tell()方法却没有更新,仍然是按照字节来读取的.这一点难道是python开发者没有注意到?
2. readlines() 读取文件的所有内容,返回结果为列表类型<list>
with open(openfile, 'r') as f: a = f.readlines() print(type(a)) print(a)结果:<class 'list'>['123456\n', '7890123']
3. readlines() 读取文件一行内容
4. tell() 返回当前指针在文件内容中的位置
5.seek(arg) 文件指针,arg参数为整型,代表在文件中的指针;seek(0) 文件开头,seek(1) 当前位置, seek(2)文件末尾
with open(openfile, 'r') as f: a = f.readline() # 读取一行内容 print(a) print(f.tell()) # 现在指针的位置 f.seek(0) # 返回到文件开始位置 a = f.readline() # 又从头开始读了 print(a)
注:seek方法对a, a+模式写文件时是不管用的,因为是追加模式,默认都会指向文件末尾
下面看一个实际应用例子,实现tail效果
import timef = open('/home/ws/test','r')f.seek(2)<span style="white-space:pre"></span># 定位到文件末尾while True: currline = f.tell() # 获取当前位置 line = f.readline() # 读入内容 if not line: # 如果当前无信息 f.seek(currline) # 继续定位在最末尾 else: print(line) # 输出内容 time.sleep(2)
文件写操作
6. write() 写文件,括号中的内容必须为str字符串类型,一次写入到文件中,如果字符串中有\n写入文件时也会换行
7. writeline() 写文件,除了可以写字符串类型外,还支持列表类型
openfile = os.path.dirname(os.path.abspath("__file__")) + "\\source3.txt"c_lines = ["abcdefg\n","higjksldf\n","dki29dfa\n"]c_str = "abcde\nssss\nccccc"with open(openfile, 'a+') as f: f.writelines(c_lines) f.write(c_str)
8.truncate() 文件截断操作,将指针后面的所有内容截取掉
with open(openfile, 'r+') as f: print(f.read()) f.seek(5) # 指针到位置5 c = f.truncate() # 截取 f.seek(0) # 指针到文件开头 print(f.read())结果:123456789012312345
文件常用操作技巧:
1. 逐行读取文件内容
with open(openfile, 'r') as f: for line in f: print(line.strip())
2. 使用stat 获取文件的信息
通过stat模块可以获取文件的一些基本信息
import osimport statopenfile = os.path.dirname(os.path.abspath("__file__")) + "\\README.md"file_stat = os.stat(openfile) # return tupleprint("file_stat info: " ,file_stat)print("file_stat mode: " , file_stat.st_mode)print("check file is dir(stat): ", stat.S_ISDIR(file_stat.st_mode))print("check file is file (os): ", os.path.isfile(openfile))print("check file is file (stat):", stat.S_ISREG(file_stat.st_mode))结果:<span style="color:#ff6666;background-color: rgb(255, 255, 255);">file_stat info: os.stat_result(st_mode=33206, st_ino=844424930202057, st_dev=2417903304, st_nlink=1, st_uid=0, st_gid=0, st_size=9, st_atime=1452135600, st_mtime=1452135607, st_ctime=1452135600)file_stat mode: 33206check file is dir(stat): Falsecheck file is file (os): Truecheck file is file (stat): True</span>stat 模块常用函数:
stat.S_ISREG(st_mode) == os.path.isfile(filename) # 判断是否一般文件
stat.S_ISDIR(st_mode) == os.path.isdir(filename) # 判断是否为文件夹
stat.S_ISLNK(st_mode) == os.path.islink(filename) # 判断是否链接文件
stat.S_ISSOCK(st_mode) # 判断是否套接字文件
stat.S_ISFIFO(st_mode) # 判断是否命名管道
stat.S_ISBLK(st_mode) # 判断是否块设备
stat.S_ISCHR(st_mode) # 判断是否字符设置
stat 模块常用属性
openfile = os.path.dirname(os.path.abspath("__file__")) + "\\README.md"file_stat = os.stat(openfile) # return tupleprint("st_mode:", file_stat.st_mode) # 权限模式print("st_ino:", file_stat.st_ino) # inode numberprint("st_dev:", file_stat.st_dev) # deviceprint("st_size:", file_stat.st_size) # 文件的大小,以位为单位print("uid:", file_stat.st_uid) # 所有用户的user idprint("gid:", file_stat.st_gid) # 所有用户的group idprint("st_atime:", file_stat.st_atime) # 文件最后访问时间print("st_mtime:", file_stat.st_mtime) # 文件最后修改时间print("st_ctime:", file_stat.st_ctime) # 文件创建时间结果:st_mode: 33206st_ino: 844424930202057st_dev: 2417903304st_size: 9uid: 0gid: 0st_atime: 1452135600.2344666st_mtime: 1452135607.5388844st_ctime: 1452135600.23446663 从一个文件写入到另一文件
openfilepath = os.path.dirname(os.path.abspath("__file__"))file1 = openfilepath + "\\1.txt"file2 = openfilepath + "\\2.txt"with open(file1,'r') as f1,open(file2,'a+') as f2: f2.write(f1.read())
- Python系列之 - python文件操作
- python之文件操作
- python之文件操作
- python 之文件操作
- python 之文件操作
- python之文件操作
- Python之文件操作
- python之文件操作
- python之文件操作
- python之文件操作
- python之文件操作
- Python之文件操作
- Python之文件操作
- Python 之文件操作
- PYTHON笔记之文件操作
- Python学习之文件操作
- Python学习之文件操作
- Python之操作Excel文件
- Android拨打电话与发送信息
- linux目录详细
- 系统架构设计理论与原则、负载均衡及高可用系统设计速记
- DEP: Ret2Libc via VirtualProtect()
- Android自动化-双击操作
- Python系列之 - python文件操作
- Sicily 1636. Show me the money
- shell处理文件
- Oracle数字型,字符型,日期型函数
- windows配置php时显示Loaded Configuration File:None
- rabbitMq学习笔记(未完)
- Android studio中常用插件
- 批量插入
- linux下文件名的操作