操作文件时,一般需要经历如下步骤:
- 打开文件
- 操作文件
一、打开文件
文件句柄
=
file
(
'文件路径'
,
'模式'
)
注:python中打开文件有两种方式,即:open(...) 和 file(...) ,本质上前者在内部会调用后者来进行文件操作,推荐使用 open。
打开文件时,需要指定文件路径和以何等方式打开文件,打开后,即可获取该文件句柄,日后通过此文件句柄对该文件操作。
打开文件的模式有:
- r,只读模式(默认)。
- w,只写模式。【不可读;不存在则创建;存在则删除内容;】
- a,追加模式。【可读; 不存在则创建;存在则只追加内容;】
"+" 表示可以同时读写某个文件
- r+,可读写文件。【可读;可写;可追加】
- w+,写读
- a+,同a
"U"表示在读取时,可以将 \r \n \r\n自动转换成 \n (与 r 或 r+ 模式同使用)
- rU
- r+U
"b"表示处理二进制文件(如:FTP发送上传ISO镜像文件,linux可忽略,windows处理二进制文件时需标注)
- rb
- wb
- ab
二、操作操作
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 """ flush() -> None. Flush the internal I/O buffer. """
26 pass
27
28
29 def isatty(self): # real signature unknown; restored from __doc__
30 判断文件是否是同意tty设备
31 """ isatty() -> true or false. True if the file is connected to a tty device. """
32 return False
33
34
35 def next(self): # real signature unknown; restored from __doc__
36 获取下一行数据,不存在,则报错
37 """ x.next() -> the next value, or raise StopIteration """
38 pass
39
40 def read(self, size=None): # real signature unknown; restored from __doc__
41 读取指定字节数据
42 """
43 read([size]) -> read at most size bytes, returned as a string.
44
45 If the size argument is negative or omitted, read until EOF is reached.
46 Notice that when in non-blocking mode, less data than what was requested
47 may be returned, even if no size parameter was given.
48 """
49 pass
50
51 def readinto(self): # real signature unknown; restored from __doc__
52 读取到缓冲区,不要用,将被遗弃
53 """ readinto() -> Undocumented. Don't use this; it may go away. """
54 pass
55
56 def readline(self, size=None): # real signature unknown; restored from __doc__
57 仅读取一行数据
58 """
59 readline([size]) -> next line from the file, as a string.
60
61 Retain newline. A non-negative size argument limits the maximum
62 number of bytes to return (an incomplete line may be returned then).
63 Return an empty string at EOF.
64 """
65 pass
66
67 def readlines(self, size=None): # real signature unknown; restored from __doc__
68 读取所有数据,并根据换行保存值列表
69 """
70 readlines([size]) -> list of strings, each a line from the file.
71
72 Call readline() repeatedly and return a list of the lines so read.
73 The optional size argument, if given, is an approximate bound on the
74 total number of bytes in the lines returned.
75 """
76 return []
77
78 def seek(self, offset, whence=None): # real signature unknown; restored from __doc__
79 指定文件中指针位置
80 """
81 seek(offset[, whence]) -> None. Move to new file position.
82
83 Argument offset is a byte count. Optional argument whence defaults to
84 0 (offset from start of file, offset should be >= 0); other values are 1
85 (move relative to current position, positive or negative), and 2 (move
86 relative to end of file, usually negative, although many platforms allow
87 seeking beyond the end of a file). If the file is opened in text mode,
88 only offsets returned by tell() are legal. Use of other offsets causes
89 undefined behavior.
90 Note that not all file objects are seekable.
91 """
92 pass
93
94 def tell(self): # real signature unknown; restored from __doc__
95 获取当前指针位置
96 """ tell() -> current file position, an integer (may be a long integer). """
97 pass
98
99 def truncate(self, size=None): # real signature unknown; restored from __doc__
100 截断数据,仅保留指定之前数据
101 """
102 truncate([size]) -> None. Truncate the file to at most size bytes.
103
104 Size defaults to the current file position, as returned by tell().
105 """
106 pass
107
108 def write(self, p_str): # real signature unknown; restored from __doc__
109 写内容
110 """
111 write(str) -> None. Write string str to file.
112
113 Note that due to buffering, flush() or close() may be needed before
114 the file on disk reflects the data written.
115 """
116 pass
117
118 def writelines(self, sequence_of_strings): # real signature unknown; restored from __doc__
119 将一个字符串列表写入文件
120 """
121 writelines(sequence_of_strings) -> None. Write the strings to the file.
122
123 Note that newlines are not added. The sequence can be any iterable object
124 producing strings. This is equivalent to calling write() for each string.
125 """
126 pass
127
128 def xreadlines(self): # real signature unknown; restored from __doc__
129 可用于逐行读取文件,非全部
130 """
131 xreadlines() -> returns self.
132
133 For backward compatibility. File objects now include the performance
134 optimizations previously implemented in the xreadlines module.
135 """
136 pass
View Code
三、with
为了避免打开文件后忘记关闭,可以通过管理上下文,即:
1 with open('log','r') as f:
2
3 ...
如此方式,当with代码块执行完毕时,内部会自动关闭并释放文件资源。
在Python 2.7 后,with又支持同时对多个文件的上下文进行管理,即:
1 with open('log1') as obj1, open('log2') as obj2:
2 pass
四、那么问题来了...
1、如何在线上环境优雅的修改配置文件?
问题
修改
1 1、查
2 输入:www.oldboy.org
3 获取当前backend下的所有记录
4
5 2、新建
6 输入:
7 arg = {
8 'bakend': 'www.oldboy.org',
9 'record':{
10 'server': '100.1.7.9',
11 'weight': 20,
12 'maxconn': 30
13 }
14 }
15
16 3、删除
17 输入:
18 arg = {
19 'bakend': 'www.oldboy.org',
20 'record':{
21 'server': '100.1.7.9',
22 'weight': 20,
23 'maxconn': 30
24 }
25 }
26
27 修改
demo