Python文件操作
在Python中一个文件,就是一个操作对象,通过不同属性即可对文件进行各种操作。Python中提供了许多的内置函数和方法能够对文件进行基本操作。
Python对文件的操作概括来说:1. 打开文件 2.操作文件 3.关闭文件
1. 打开文件、关闭文件
Python中使用open函数打开一个文件,创建一个file操作对象。
open()方法
语法:
file object = open(file_name [, access_mode][, buffering])
各个参数的细节如下:
- file_name:file_name变量是一个包含了你要访问的文件名称的字符串值。
- access_mode:access_mode决定了打开文件的模式:只读,写入,追加等。所有可取值见如下的完全列表。这个参数是非强制的,默认文件访问模式为只读(r)。
- buffering:如果buffering的值被设为0,就不会有寄存。如果buffering的值取1,访问文件时会寄存行。如果将buffering的值设为大于1的整数,表明了这就是的寄存区的缓冲大小。如果取负值,寄存区的缓冲大小则为系统默认。
不同模式打开文件的完全列表:
一个文件打开后你将得到一个file对象,通过对这个对象的不同属性进行操作,你可以得到有关该文件的各种信息。
file对象打开后所有属性的列表:
关闭文件
Close()方法
File对象的close()方法刷新缓冲区里任何还没写入的信息,并关闭该文件,这之后便不能再进行写入。
举例:打开关闭文件
#!/usr/bin/python
# -*- coding: UTF-8 -*- # 打开一个文件
fo = open("foo.txt", "wb")
print "Name of the file: ", fo.name # 关闭打开的文件
fo.close()
结果:
Name of the file: foo.txt
文件操作源码
class file(object): def close(self): # real signature unknown; restored from __doc__
关闭文件 """close() -> None or (perhaps) an integer. Close the file. Sets data attribute .closed to True. A closed file cannot be used for
further I/O operations. close() may be called more than once without
error. Some kinds of file objects (for example, opened by popen())
may return an exit status upon closing.
""" def fileno(self): # real signature unknown; restored from __doc__
文件描述符 """fileno() -> integer "file descriptor". This is needed for lower-level file interfaces, such os.read(). """ return def flush(self): # real signature unknown; restored from __doc__
刷新文件内部缓冲区 """ flush() -> None. Flush the internal I/O buffer. """ pass def isatty(self): # real signature unknown; restored from __doc__
判断文件是否是同意tty设备 """ isatty() -> true or false. True if the file is connected to a tty device. """ return False def next(self): # real signature unknown; restored from __doc__
获取下一行数据,不存在,则报错 """ x.next() -> the next value, or raise StopIteration """ pass def read(self, size=None): # real signature unknown; restored from __doc__
读取指定字节数据 """read([size]) -> read at most size bytes, returned as a string. If the size argument is negative or omitted, read until EOF is reached.
Notice that when in non-blocking mode, less data than what was requested
may be returned, even if no size parameter was given.""" pass def readinto(self): # real signature unknown; restored from __doc__
读取到缓冲区,不要用,将被遗弃 """ readinto() -> Undocumented. Don't use this; it may go away. """ pass def readline(self, size=None): # real signature unknown; restored from __doc__
仅读取一行数据
"""readline([size]) -> next line from the file, as a string. Retain newline. A non-negative size argument limits the maximum
number of bytes to return (an incomplete line may be returned then).
Return an empty string at EOF. """ pass def readlines(self, size=None): # real signature unknown; restored from __doc__
读取所有数据,并根据换行保存值列表 """readlines([size]) -> list of strings, each a line from the file. Call readline() repeatedly and return a list of the lines so read.
The optional size argument, if given, is an approximate bound on the
total number of bytes in the lines returned. """ return [] def seek(self, offset, whence=None): # real signature unknown; restored from __doc__
指定文件中指针位置
"""seek(offset[, whence]) -> None. Move to new file position. Argument offset is a byte count. Optional argument whence defaults to
(offset from start of file, offset should be >= ); other values are
(move relative to current position, positive or negative), and (move
relative to end of file, usually negative, although many platforms allow
seeking beyond the end of a file). If the file is opened in text mode,
only offsets returned by tell() are legal. Use of other offsets causes
undefined behavior.
Note that not all file objects are seekable. """ pass def tell(self): # real signature unknown; restored from __doc__
获取当前指针位置 """ tell() -> current file position, an integer (may be a long integer). """
pass def truncate(self, size=None): # real signature unknown; restored from __doc__
截断数据,仅保留指定之前数据 """ truncate([size]) -> None. Truncate the file to at most size bytes. Size defaults to the current file position, as returned by tell().“"" pass def write(self, p_str): # real signature unknown; restored from __doc__
写内容 """write(str) -> None. Write string str to file. Note that due to buffering, flush() or close() may be needed before
the file on disk reflects the data written.""" pass def writelines(self, sequence_of_strings): # real signature unknown; restored from __doc__
将一个字符串列表写入文件
"""writelines(sequence_of_strings) -> None. Write the strings to the file. Note that newlines are not added. The sequence can be any iterable object
producing strings. This is equivalent to calling write() for each string. """ pass def xreadlines(self): # real signature unknown; restored from __doc__
可用于逐行读取文件,非全部 """xreadlines() -> returns self. For backward compatibility. File objects now include the performance
optimizations previously implemented in the xreadlines module. """ pass file Code
2. 文件操作
a)read 读操作
read()方法从一个打开的文件中读取一个字符串。需要重点注意的是,Python字符串可以是二进制数据,而不是仅仅是文字。一次性将所有文件读取为一个大的字符串。
语法:
fileObject.read([count]);
在这里,被传递的参数是要从已打开文件中读取的字节计数。该方法从文件的开头开始读入,如果没有传入count,它会尝试尽可能多地读取更多的内容,很可能是直到文件的末尾。
例子:有一个内容如下的文本
Python is a great language.
Yeah its great!!
#!/usr/bin/python
# -*- coding: UTF-8 -*- # 打开一个文件
fo = open("/tmp/foo.txt", "r+")
str = fo.read(10);
print "Read String is : ", str
# 关闭打开的文件
fo.close()
b)readline
readline() 方法用于从文件读取整行,包括 "\n" 字符。如果指定了一个非负数的参数,则返回指定大小的字节数,包括 "\n" 字符。每次读取一行,一行一行迭代读取
语法:
readline([size]) 方法语法如下: #size -- 从文件中读取的字节数。
runoob.txt 的内容如下:
1:www.runoob.com
2:www.runoob.com
3:www.runoob.com
4:www.runoob.com
5:www.runoob.com
读取文件内容
#!/usr/bin/python
# -*- coding: UTF-8 -*- # 打开文件
fo = open("runoob.txt", "rw+")
print "文件名为: ", fo.name line = fo.readline()
print "读取第一行 %s" % (line) line = fo.readline(5)
print "读取的字符串为: %s" % (line) # 关闭文件
fo.close()
输出结果
文件名为: runoob.txt
读取第一行 1:www.runoob.com 读取的字符串为: 2:www
C) readlines
readlines() 方法用于读取所有行(直到结束符 EOF)并返回列表,若给定sizeint>0,返回总和大约为sizeint字节的行, 实际读取值可能比sizhint较大, 因为需要填充缓冲区。
一次读取文件所有内容,以每行一个分隔,形成一个大的列表
如果碰到结束符 EOF 则返回空字符串。
语法:
fileObject.readlines( sizehint ); #sizeint为读取的行数
返回值
返回列表,包含所有的行。
举例:读取上边runoob.txt文本
#!/usr/bin/python
# -*- coding: UTF-8 -*- # 打开文件
fo = open("runoob.txt", "rw+")
print "文件名为: ", fo.name line = fo.readlines()
print "读取的数据为: %s" % (line) line = fo.readlines(2)
print "读取的数据为: %s" % (line) # 关闭文件
fo.close()
结果:
文件名为: runoob.txt
读取的数据为: ['1:www.runoob.com\n', '2:www.runoob.com\n', '3:www.runoob.com\n', '4:www.runoob.com\n', '5:www.runoob.com\n']
读取的数据为: []
D) 写操作
Write()方法可将任何字符串写入一个打开的文件。需要重点注意的是,Python字符串可以是二进制数据,而不是仅仅是文字。
Write()方法不在字符串的结尾不添加换行符('\n'):
语法:
fileObject.write(string); #string代表要写入文件的内容
举例
#!/usr/bin/python
# -*- coding: UTF-8 -*- # 打开一个文件
fo = open("/tmp/a.txt", "wb")
fo.write( "Python is a great language.\nYeah its great!!\n"); # 关闭打开的文件
fo.close()
上述方法会创建foo.txt文件,并将收到的内容写入该文件,并最终关闭文件。如果你打开这个文件,将看到以下内容:
Python is a great language.
Yeah its great!!
E) writelines
writelines() 方法用于向文件中写入一序列的字符串。这一序列字符串可以是由迭代对象产生的,如一个字符串列表。
换行需要制定换行符 \n。
语法:
fileObject.writelines( [ str ]) # str为要写入的字符串序列
该方法没有返回值。
#!/usr/bin/python
# -*- coding: UTF-8 -*- # 打开文件
fo = open("test.txt", "w")
print "文件名为: ", fo.name
seq = ["菜鸟教程 1\n", "菜鸟教程 2"]
fo.writelines( seq ) # 关闭文件
fo.close()
以上实例输出结果为:
文件名为: test.txt
查看文件内容:
$ cat test.txt
菜鸟教程 1
菜鸟教程 2
F) 文件位置:
Tell()方法告诉你文件内的当前位置;换句话说,下一次的读写会发生在文件开头这么多字节之后:
seek(offset [,from])方法改变当前文件的位置。Offset变量表示要移动的字节数。From变量指定开始移动字节的参考位置。
如果from被设为0,这意味着将文件的开头作为移动字节的参考位置。
如果设为1,则使用当前的位置作为参考位置。
如果它被设为2,那么该文件的末尾将作为参考位置。
#!/usr/bin/python
# -*- coding: UTF-8 -*- # 打开一个文件
fo = open("/tmp/foo.txt", "r+")
str = fo.read(10);
print "Read String is : ", str # 查找当前位置
position = fo.tell();
print "Current file position : ", position # 把指针再次重新定位到文件开头
position = fo.seek(0, 0);
str = fo.read(10);
print "Again read String is : ", str
# 关闭打开的文件
fo.close()
结果:
Read String is : Python is
Current file position : 10
Again read String is : Python is
G)with
为了避免打开文件后忘记关闭,可以通过管理上下文,即:
with open('log','r') as f:
如此方式,当with代码块执行完毕时,内部会自动关闭并释放文件资源。
在Python 2.7 后,with又支持同时对多个文件的上下文进行管理,即:
with open('log1') as obj1, open('log2') as obj2:
pass
线上文件修改举例
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import json
import os def fetch(backend):
backend_title = 'backend %s' % backend
record_list = []
with open('ha') as obj:
flag = False
for line in obj:
line = line.strip()
if line == backend_title:
flag = True
continue
if flag and line.startswith('backend'):
flag = False
break if flag and line:
record_list.append(line) return record_list def add(dict_info):
backend = dict_info.get('backend')
record_list = fetch(backend)
backend_title = "backend %s" % backend
current_record = "server %s %s weight %d maxconn %d" % (dict_info['record']['server'], dict_info['record']['server'], dict_info['record']['weight'], dict_info['record']['maxconn'])
if not record_list:
record_list.append(backend_title)
record_list.append(current_record)
with open('ha') as read_file, open('ha.new', 'w') as write_file:
flag = False
for line in read_file:
write_file.write(line)
for i in record_list:
if i.startswith('backend'):
write_file.write(i+'\n')
else:
write_file.write("%s%s\n" % (8*" ", i))
else:
record_list.insert(0, backend_title)
if current_record not in record_list:
record_list.append(current_record) with open('ha') as read_file, open('ha.new', 'w') as write_file:
flag = False
has_write = False
for line in read_file:
line_strip = line.strip()
if line_strip == backend_title:
flag = True
continue
if flag and line_strip.startswith('backend'):
flag = False
if not flag:
write_file.write(line)
else:
if not has_write:
for i in record_list:
if i.startswith('backend'):
write_file.write(i+'\n')
else:
write_file.write("%s%s\n" % (8*" ", i))
has_write = True
os.rename('ha','ha.bak')
os.rename('ha.new','ha') def remove(dict_info):
backend = dict_info.get('backend')
record_list = fetch(backend)
backend_title = "backend %s" % backend
current_record = "server %s %s weight %d maxconn %d" % (dict_info['record']['server'], dict_info['record']['server'], dict_info['record']['weight'], dict_info['record']['maxconn'])
if not record_list:
return
else:
if current_record not in record_list:
return
else:
del record_list[record_list.index(current_record)]
if len(record_list) > 0:
record_list.insert(0, backend_title)
with open('ha') as read_file, open('ha.new', 'w') as write_file:
flag = False
has_write = False
for line in read_file:
line_strip = line.strip()
if line_strip == backend_title:
flag = True
continue
if flag and line_strip.startswith('backend'):
flag = False
if not flag:
write_file.write(line)
else:
if not has_write:
for i in record_list:
if i.startswith('backend'):
write_file.write(i+'\n')
else:
write_file.write("%s%s\n" % (8*" ", i))
has_write = True
os.rename('ha','ha.bak')
os.rename('ha.new','ha') if __name__ == '__main__':
"""
print '1、获取;2、添加;3、删除'
num = raw_input('请输入序号:')
data = raw_input('请输入内容:')
if num == '1':
fetch(data)
else:
dict_data = json.loads(data)
if num == '2':
add(dict_data)
elif num == '3':
remove(dict_data)
else:
pass
"""
#data = "www.oldboy.org"
#fetch(data)
#data = '{"backend": "tettst.oldboy.org","record":{"server": "100.1.7.90","weight": 20,"maxconn": 30}}'
#dict_data = json.loads(data)
#add(dict_data)
#remove(dict_data) demo