博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python学习笔记十-文件操作
阅读量:5065 次
发布时间:2019-06-12

本文共 7180 字,大约阅读时间需要 23 分钟。

对文件操作流程


1、打开文件,得到文件句柄并赋值给一个变量

2、通过句柄对文件进行操作

3、关闭文件

操作如下:

花间一壶酒,独酌无相亲。举杯邀明月,对影成三人。月既不解饮,影徒随我身。暂伴月将影,行乐须及春。我歌月徘徊,我舞影零乱。醒时同交欢,醉后各分散。永结无情游,相期邈云汉。f = open('月下独酌', 'r', encoding = 'utf8') #打开文件data = f.read() #读取文件f.close() #关闭文件

 

注意 if in the win,hello文件是utf8保存的,打开文件时open函数是通过操作系统打开的文件,而win操作系统

默认的是gbk编码,所以直接打开会乱码,需要f=open('hello',encoding='utf8'),hello文件如果是gbk保存的,则直接打开即可。

文件打开模式


 
========= ===============================================================    Character Meaning    --------- ---------------------------------------------------------------    'r'       open for reading (default)    'w'       open for writing, truncating the file first    'x'       create a new file and open it for writing    'a'       open for writing, appending to the end of the file if it exists    'b'       binary mode    't'       text mode (default)    '+'       open a disk file for updating (reading and writing)    'U'       universal newline mode (deprecated)  ========= ===============================================================

三种基本模式

# f = open('月下独酌','w') #打开文件# f = open('月下独酌','a') #打开文件# f.write('莫等闲1\n')# f.write('白了少年头2\n')# f.write('空悲切!3')

 文件具体操作


 

def read(self, size=-1): # known case of _io.FileIO.read        """        注意,不一定能全读回来        Read at most size bytes, returned as bytes.        Only makes one system call, so less data may be returned than requested.        In non-blocking mode, returns None if no data is available.        Return an empty bytes object at EOF.        """        return ""def readline(self, *args, **kwargs):        passdef readlines(self, *args, **kwargs):        passdef tell(self, *args, **kwargs): # real signature unknown        """        Current file position.        Can raise OSError for non seekable files.        """        passdef seek(self, *args, **kwargs): # real signature unknown        """        Move to new file position and return the file position.        Argument offset is a byte count.  Optional argument whence defaults to        SEEK_SET or 0 (offset from start of file, offset should be >= 0); other values        are SEEK_CUR or 1 (move relative to current position, positive or negative),        and SEEK_END or 2 (move relative to end of file, usually negative, although        many platforms allow seeking beyond the end of a file).        Note that not all file objects are seekable.        """        passdef write(self, *args, **kwargs): # real signature unknown        """        Write bytes b to file, return number written.        Only makes one system call, so not all of the data may be written.        The number of bytes actually written is returned.  In non-blocking mode,        returns None if the write would block.        """        passdef flush(self, *args, **kwargs):        passdef truncate(self, *args, **kwargs): # real signature unknown        """        Truncate the file to at most size bytes and return the truncated size.        Size defaults to the current file position, as returned by tell().        The current file position is changed to the value of size.        """        passdef close(self): # real signature unknown; restored from __doc__            """            Close the file.            A closed file cannot be used for further I/O operations.  close() may be            called more than once without error.            """            pass##############################################################less usefull    def fileno(self, *args, **kwargs): # real signature unknown            """ Return the underlying file descriptor (an integer). """            pass    def isatty(self, *args, **kwargs): # real signature unknown        """ True if the file is connected to a TTY device. """        pass    def readable(self, *args, **kwargs): # real signature unknown        """ True if file was opened in a read mode. """        pass    def readall(self, *args, **kwargs): # real signature unknown        """        Read all data from the file, returned as bytes.        In non-blocking mode, returns as much as is immediately available,        or None if no data is available.  Return an empty bytes object at EOF.        """        pass    def seekable(self, *args, **kwargs): # real signature unknown        """ True if file supports random-access. """        pass    def writable(self, *args, **kwargs): # real signature unknown        """ True if file was opened in a write mode. """        pass操作方法介绍
View Code
f = open('小重山') #打开文件# data1=f.read()#获取文件内容# data2=f.read()#获取文件内容## print(data1)# print('...',data2)# data=f.read(5)#获取文件内容 # data=f.readline()# data=f.readline()# print(f.__iter__().__next__())# for i in range(5):#     print(f.readline()) # data=f.readlines() # for line in f.readlines():#     print(line)  # 问题来了:打印所有行,另外第3行后面加上:'end 3'# for index,line in enumerate(f.readlines()):#     if index==2:#         line=''.join([line.strip(),'end 3'])#     print(line.strip()) #切记:以后我们一定都用下面这种# count=0# for line in f:#     if count==3:#         line=''.join([line.strip(),'end 3'])#     print(line.strip())#     count+=1 # print(f.tell())# print(f.readline())# print(f.tell())#tell对于英文字符就是占一个,中文字符占三个,区分与read()的不同.# print(f.read(5))#一个中文占三个字符# print(f.tell())# f.seek(0)# print(f.read(6))#read后不管是中文字符还是英文字符,都统一算一个单位,read(6),此刻就读了6个中文字符 #terminal上操作:f = open('小重山2','w')# f.write('hello \n')# f.flush()# f.write('world') # 应用:进度条# import time,sys# for i in range(30):#     sys.stdout.write("*")#     # sys.stdout.flush()#     time.sleep(0.1)  # f = open('小重山2','w')# f.truncate()#全部截断# f.truncate(5)#全部截断  # print(f.isatty())# print(f.seekable())# print(f.readable()) f.close() #关闭文件

 接下来我们继续扩展文件模式:

# f = open('小重山2','w') #打开文件# f = open('小重山2','a') #打开文件# f.write('莫等闲1\n')# f.write('白了少年头2\n')# f.write('空悲切!3')  # f.close() #r+,w+模式# f = open('小重山2','r+') #以读写模式打开文件# print(f.read(5))#可读# f.write('hello')# print('------')# print(f.read())  # f = open('小重山2','w+') #以写读模式打开文件# print(f.read(5))#什么都没有,因为先格式化了文本# f.write('hello alex')# print(f.read())#还是read不到# f.seek(0)# print(f.read()) #w+与a+的区别在于是否在开始覆盖整个文件  # ok,重点来了,我要给文本第三行后面加一行内容:'hello 岳飞!'# 有同学说,前面不是做过修改了吗? 大哥,刚才是修改内容后print,现在是对文件进行修改!!!# f = open('小重山2','r+') #以写读模式打开文件# f.readline()# f.readline()# f.readline()# print(f.tell())# f.write('hello 岳飞')# f.close()# 和想的不一样,不管事!那涉及到文件修改怎么办呢? # f_read = open('小重山','r') #以写读模式打开文件# f_write = open('小重山_back','w') #以写读模式打开文件 # count=0# for line in f_read:    # if count==3:    #     f_write.write('hello,岳飞\n')    #    # else:    #     f_write.write(line)      # another way:    # if count==3:    #    #     line='hello,岳飞2\n'    # f_write.write(line)    # count+=1  # #二进制模式# f = open('小重山2','wb') #以二进制的形式读文件# # f = open('小重山2','wb') #以二进制的形式写文件# f.write('hello alvin!'.encode())#b'hello alvin!'就是一个二进制格式的数据,只是为了观看,没有显示成010101的形式

 

注意1:  无论是py2还是py3,在r+模式下都可以等量字节替换,但没有任何意义的! 

注意2:有同学在这里会用readlines得到内容列表,再通过索引对相应内容进行修改,最后将列表重新写会该文件。

           这种思路有一个很大的问题,数据若很大,你的内存会受不了的,而我们的方式则可以通过迭代器来优化这个过程。

whih语句


 

为了避免打开文件后忘记关闭,可以通过管理上下文,即:

 

with open('log','r') as f:        pass

如此方式,当with代码块执行完毕时,内部会自动关闭并释放文件资源。

在Python 2.7 后,with又支持同时对多个文件的上下文进行管理,即:

with open('log1') as obj1, open('log2') as obj2:    pass

 

 

转载于:https://www.cnblogs.com/zhangjiuzheng/p/10554913.html

你可能感兴趣的文章
Hibernate原理
查看>>
flash、div、iframe的层级
查看>>
MVVM架构的理解
查看>>
[转]使用HttpOnly提升Cookie安全性
查看>>
ubuntu 14.04 如何设置静态ip
查看>>
JSZip
查看>>
hdu 3339 In Action 背包+flyod
查看>>
设计模式:策略模式(Strategy)
查看>>
软件工程之我见
查看>>
Core-3399-JD4 六核高性能AI核心板
查看>>
DS18B20读数错误排除
查看>>
VS2010建立Windows服务项目时的一些问题
查看>>
网络流 增广路 回退
查看>>
日期年月日的比较以及判断
查看>>
【初码干货】关于.NET玩爬虫这些事
查看>>
让iframe可编辑
查看>>
Wikioi 1222 信与信封问题(二分图匹配)
查看>>
SQL Server 事务、异常和游标
查看>>
SQLServer删除登录帐户
查看>>
[数据结构]之链表
查看>>