python-文件操作
文件操作
文件的操作,一般需要经历如下步骤:
- 打开文件
- 操作文件
- 关闭文件
一.打开文件
python打开文件有两种方式,即:open(...)和file(...)
本质上前者在内部会调用后者来进行文件操作,推荐使用 open。3.0以后file方法讲被用做其他,open方法会自动的去帮你找他调用得方法在那里!
1 文件句柄 = open('文件路径','模式') #文件全路径
打开文件时,需要指定文件路径和以何等方式打开文件,打开后,即可获取该文件句柄,日后通过此文件句柄对该文件操作。
打开文件的模式有:
- r,只读模式(默认)。
- w,只写模式。【不可读;不存在则创建,存在则清空内容】
- a,追加模式。【可读;不存在则创建,存在则只追加内容】
'+'表示可以同时读写某个文件
- r+,可读取文件。【可读,可写,可追加】
- w+,先写再读,【这个方法打开文件会清空原本文件中的所有内容,将新的内容写进去,之后可以读取已经写入的内容】
- a+,同a
"b"表示以字节的方式操作
- rb 或 r+b
- wb 或 w+b
- xb 或 w+b
- ab 或 a+b
r和rb的区别:
二、操作
1 class file(object): 2 3 def close(self): # real signature unknown; restored from __doc__ 4 关闭文件 5 6 """close() -> None or (perhaps) an integer. Close the file. 7 8 Sets data attribute .closed to True. A closed file cannot be used for 9 further I/O operations. close() may be called more than once without 10 error. Some kinds of file objects (for example, opened by popen()) 11 may return an exit status upon closing. 12 """ 13 14 def fileno(self): # real signature unknown; restored from __doc__ 15 文件描述符 16 17 """fileno() -> integer "file descriptor". 18 19 This is needed for lower-level file interfaces, such os.read(). """ 20 21 return 0 22 23 def flush(self): # real signature unknown; restored from __doc__ 24 刷新文件内部缓冲区 25 26 """ flush() -> None. Flush the internal I/O buffer. """ 27 28 pass 29 30 def isatty(self): # real signature unknown; restored from __doc__ 31 判断文件是否是同意tty设备 32 33 """ isatty() -> true or false. True if the file is connected to a tty device. """ 34 35 return False 36 37 def next(self): # real signature unknown; restored from __doc__ 38 获取下一行数据,不存在,则报错 39 40 """ x.next() -> the next value, or raise StopIteration """ 41 42 pass 43 44 45 46 def read(self, size=None): # real signature unknown; restored from __doc__ 47 读取指定字节数据 48 49 """read([size]) -> read at most size bytes, returned as a string. 50 51 If the size argument is negative or omitted, read until EOF is reached. 52 Notice that when in non-blocking mode, less data than what was requested 53 may be returned, even if no size parameter was given.""" 54 55 pass 56 57 def readinto(self): # real signature unknown; restored from __doc__ 58 读取到缓冲区,不要用,将被遗弃 59 60 """ readinto() -> Undocumented. Don't use this; it may go away. """ 61 62 pass 63 64 65 def readline(self, size=None): # real signature unknown; restored from __doc__ 66 仅读取一行数据 67 """readline([size]) -> next line from the file, as a string. 68 69 Retain newline. A non-negative size argument limits the maximum 70 number of bytes to return (an incomplete line may be returned then). 71 Return an empty string at EOF. """ 72 73 pass 74 75 def readlines(self, size=None): # real signature unknown; restored from __doc__ 76 读取所有数据,并根据换行保存值列表 77 78 """readlines([size]) -> list of strings, each a line from the file. 79 80 Call readline() repeatedly and return a list of the lines so read. 81 The optional size argument, if given, is an approximate bound on the 82 total number of bytes in the lines returned. """ 83 84 return [] 85 86 87 88 def seek(self, offset, whence=None): # real signature unknown; restored from __doc__ 89 指定文件中指针位置 90 """seek(offset[, whence]) -> None. Move to new file position. 91 92 Argument offset is a byte count. Optional argument whence defaults to 93 0 (offset from start of file, offset should be >= 0); other values are 1 94 (move relative to current position, positive or negative), and 2 (move 95 relative to end of file, usually negative, although many platforms allow 96 seeking beyond the end of a file). If the file is opened in text mode, 97 only offsets returned by tell() are legal. Use of other offsets causes 98 undefined behavior. 99 Note that not all file objects are seekable. """ 100 101 pass 102 103 104 105 def tell(self): # real signature unknown; restored from __doc__ 106 获取当前指针位置 107 108 """ tell() -> current file position, an integer (may be a long integer). """ 109 pass 110 111 112 def truncate(self, size=None): # real signature unknown; restored from __doc__ 113 截断数据,仅保留指定之前数据 114 115 """ truncate([size]) -> None. Truncate the file to at most size bytes. 116 117 Size defaults to the current file position, as returned by tell().“"" 118 119 pass 120 121 122 123 def write(self, p_str): # real signature unknown; restored from __doc__ 124 写内容 125 126 """write(str) -> None. Write string str to file. 127 128 Note that due to buffering, flush() or close() may be needed before 129 the file on disk reflects the data written.""" 130 131 pass 132 133 def writelines(self, sequence_of_strings): # real signature unknown; restored from __doc__ 134 将一个字符串列表写入文件 135 """writelines(sequence_of_strings) -> None. Write the strings to the file. 136 137 Note that newlines are not added. The sequence can be any iterable object 138 producing strings. This is equivalent to calling write() for each string. """ 139 140 pass 141 142 143 144 def xreadlines(self): # real signature unknown; restored from __doc__ 145 可用于逐行读取文件,非全部 146 147 """xreadlines() -> returns self. 148 149 For backward compatibility. File objects now include the performance 150 optimizations previously implemented in the xreadlines module. """ 151 152 pass 153 154 file Code
读文件操作:
read([size]):读取文件全部内容,如果设置了size,那么就读取size字节。
1 # 以只读的方式打开文件ha2.log 2 f = open("hello.txt","r") 3 # 读取文件内容赋值给变量c 4 a = f.read(6) #如果加size,则读取size个字符, 注意读取指针的位置 但是如果文件过大,可能造成内存溢出问题 5 b = f.read() #如果没加size,则全部读取。 注意,会根据上面的指针继续读取到结尾。 6 # 关闭文件 7 f.close() 8 # 输出a,b的值 9 print 'a=', a 10 print 'b=', b
输出结果:
a= 66666
b= 667777
dasdasdadsa
asdasdasdasd
asdasdads22222222
ha2.log文件内容:
readline([size]):仅读取一行数据,如果设置了size,那么就读取size字节。
1 #以只读的方式打开文件hello.txt 2 f = open('ha2.log','r') 3 # 读取文件内容赋值给变量c 4 a = f.readline(5) #只读取一行,如果加了size 只去读对应数量的字符 5 b = f.readline() #只读取一行,如果没加size 只去一整行。 6 c = f.readline()#每调用一次,读取一行 7 # 关闭文件 8 f.close() 9 # 输出a,b的值 10 print 'a=',a 11 print 'b=',b 12 print 'c=',c
readlines():读取所有数据,并根据换行保存值列表.
1 #以只读的方式打开文件hello.txt 2 f = open('ha2.log','r') 3 # 读取文件内容赋值给变量c 4 a = f.readlines() #读取全部信息,并以列表的形式保存,但是如果文件过大,可能造成内存溢出问题 5 # 关闭文件 6 f.close() 7 # 输出a的值 8 print 'a=',a
写文件操作:
write(str) 将字符串写入到文件中,原文件内容存在则清空,不存在新建。
1 #以只读的方式打开文件hello.txt 2 f = open('ha2.log','w') #这个是本地存在文件,其中存在内容 3 f1 = open('ha3.log','w')#这个是本地不存在文件 4 #在文件内容中写入字符串this is a test123 5 f.write('this is a test123') 6 f.write('sssssssssssss')#如果不在上语句加上\n就会写在后面,请注意换行符的使用 7 f1.write('this is a test123') 8 f1.write('sssssssssssss') 9 #关闭文件 10 f.close() 11 f1.close()
结果:
ha2.log之前的内容: 现在的内容:
writelines(str) 功能类似只是可以写多行到文件,参数可以是一个可迭代的对象,列表、元组等。
注意:这些可迭代对象的元素必须是字符串。不然会报错 TypeError: writelines() argument must be a sequence of strings
a1 = ['111','222','333','444'] #元素必须是字符串 a2 = ('aaaa','bbbb','ccccc') a3 = {'ffff':123,'gggg':456} #以只读的方式打开文件hello.txt f = open('ha2.log','w') #这个是本地存在文件,其中存在内容 #在文件内容中写入字符串this is a test123 f.writelines(a3)#如果不在上语句加上\n就会写在后面,请注意换行符的使用 #关闭文件 f.close()
其他操作(主要→次要):
tell(self),获取指针的位置,没有参数:
1 a1 = ['111','222','333','444'] 2 a2 = ('aaaa','bbbb','ccccc') 3 a3 = {'ffff':123,'gggg':456} 4 #以可读可写的方式打开文件hello.txt 5 f = open('ha2.log','r+') #这个是本地存在文件,其中存在内容 6 #在文件内容中写入字符串this is a test123 7 print '位置1:',f.tell()#获取当前指针位置,注意在打开文件的时候指针总是在最开始的位置, 8 f.writelines(a2)#如果不在上语句加上\n就会写在后面,请注意换行符的使用 9 print '位置2:',f.tell()#获取当前指针位置 10 #关闭文件 11 f.close()
tell的作用是指出当前指针所在的位置。无论对文件的读或者写,都是依赖于指针的位置,我们从指针的位置开始读,也从指针的位置开始写。
结果:
seek(offset),上面的tell函数是获取指针的位置,seek函数可以指定文件中指针位置,这样可根据自己需要设定写入位置。
1 #以可读可写的方式打开文件hello.txt 2 f = open('ha2.log','r+') #这个是本地存在文件,其中存在内容 3 #在文件内容中写入字符串this is a test123 4 print '位置1:',f.tell()#获取当前指针位置,注意在打开文件的时候指针总是在最开始的位置, 5 f.seek(4)#指定指针的位置 6 print '位置2:',f.tell()#获取当前指针位置 7 #关闭文件 8 f.close()
truncate(size):保存当前指针位置之前的内容
1 #以可读可写的方式打开文件hello.txt 2 f = open('ha2.log','r+') #这个是本地存在文件,其中存在内容 3 print '第一次读:',f.read() 4 #在文件内容中写入字符串this is a test123 5 f.seek(0)#指定指针的位置 6 f.write('this is a truncate test,***') 7 f.seek(0)#指定指针的位置 8 f.write('test test test') 9 f.truncate() 10 f.seek(0) 11 print '第二次读:',f.read() 12 #关闭文件 13 f.close()
结果:
第一次读: 111111111111
2222222222222
44444444444444
第二次读: test test test
总结:有上面的打印结果我们可以知道,在文件进行写操作的时候,会根据指针的位置直接覆盖相应的内容,但是很多时候我们修改完文件之后,后面的东西就不想保留 了,这个时候我们使用truncate方法,文件就仅保存当前指针位置之前的内容。我们同样可以使用truncate(n)来保存n之前的内容,n表示指 针位置。
三、管理上下文
为了避免打开文件后忘记关闭,可以通过管理上下文,即:with open('文件路径','操作方式') as 文件句柄:
1 #使用whith打开可以不用close 2 with open('ha2.log','r+') as file_obj: 3 file_obj.write('')
在Python 2.7 及以后,with又支持同时对多个文件的上下文进行管理,即:
# 文件句柄可以循环,每次1句,写入 另一个文件 with open('ha2.log','r') as obj1, open('ha3.log','w') as obj2: for line in obj1: obj2.write(line)
例子:可以对原文件进行修改的时候进行备份,这样可以避免忘记备份啦,方便以后回滚文件
with open('nginx.conf','r') as obj1,open('nginx.conf.new','w') as obj2: for i in obj1.readlines(): i = i.strip() print i obj2.write(i) obj2.write('\n') #读取nginx.conf每行然后存储到新的文件nginx.conf.new里!