1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251
| open(file, mode='r', buffering=-1, encoding=None, errors=None,newline=None, closefd=True, opener=None) ```python
* file参数指定了被打开的文件名称。 * mode参数指定了打开文件后的处理方式。 * buffering参数指定了读写文件的缓存模式。0表示不缓存,1表示缓存,如大于1则表示缓冲区的大小。默认值是缓存模式。 * encoding参数指定对文本进行编码和解码的方式,**只适用于文本模式**,可以使用Python支持的任何格式,如GBK、utf8、CP936等等。
* r: 读模式(默认模式,可省略),如果文件不存在则抛出异常 * w: 写模式,如果文件已存在,先清空原有内容 * x: 写模式,创建新文件,如果文件已存在则抛出异常 * a: 追加模式,不覆盖文件中原有内容 * b: 二进制模式(可与其他模式组合使用) * t: 文本模式(默认模式,可省略) * +:读、写模式(可与其他模式组合使用) * r+:可读可写,若文件不存在,报错;w+: 可读可写,若文件不存在,创建
如果执行正常,open()函数返回1个文件对象,通过该文件对象可以对文件进行读写操作。如果指定文件不存在、访问权限不够、磁盘空间不足或其他原因导致创建文件对象失败则抛出异常。
当对文件内容操作完以后,**一定要关闭文件对象**,这样才能保证所做的任何修改都确实被保存到文件中。
```python f1 = open( 'file1.txt','r' ) f1.close() ```python
* close() 把缓冲区的内容写入文件,同时关闭文件,并释放文件对象 * flush() 把缓冲区的内容写入文件,但不关闭文件 * read([size]) 从文本文件中读取size个字符(Python 3.x)的内容作为结果返回,或从二进制文件中读取指定数量的字节并返回,如果省略size则表示读取所有内容 * readline() 从文本文件中读取一行内容作为结果返回 * readlines() 把文本文件中的每行文本作为一个字符串存入列表中,返回该列表 * seek(offset[,whence])把文件指针移动到新的字节位置,offset表示相对于whence的位置。whence为0表示从文件头开始计算,1表示从当前位置开始计算,2表示从文件尾开始计算,默认为0 * tell() 返回文件指针的当前位置 * write(s) 把s的内容写入文件 * writelines(s) 把字符串列表写入文本文件,不添加换行符
在实际开发中,读写文件应优先考虑使用上下文管理语句with,关键字with可以自动管理资源,不论因为什么原因(哪怕是代码引发了异常)跳出with块,**总能保证文件被正确关闭**,并且可以在代码块执行完毕后自动还原进入该代码块时的上下文,常用于**文件操作、数据库连接、网络连接、多线程与多进程同步时的锁对象管理**等场合。
```python with open(filename, mode, encoding) as fp: ```python
```python s ='Hello world\n我永远喜欢鹿乃\nmikudaisuki\n' with open('sample.txt','w') as fp: fp.write(s) with open('sample.txt') as fp: print(fp.read()) ```python
```python with open('sample.txt') as fp: for line in fp: print(line) ```python
```python with open('data.txt','r') as fp: data = fp.readlines() data = [int(item) for item in data] data.sort(reverse=True) data = [str(item)+'\n' for item in data] with open('data_desc.txt','w') as fp: fp.writelines(data) ```python
```python with open('sample.txt') as fp: result = [0,''] for line in fp: t = len(line) if t > result[0]: result = [t, line] print(result) ```python
对于二进制文件,不能使用记事本或其他文本编辑软件直接进行正常读写,也不能通过Python的文件对象直接读取和理解二进制文件的内容。必须**正确理解二进制文件结构和序列化规则,然后设计正确的反序列化规则**,才能准确地理解二进制文件内容。 所谓序列化,简单地说就是把内存中的数据在不丢失其类型信息的情况下转成二进制形式的过程,**对象序列化后的数据经过正确的反序列化过程应该能够准确无误地恢复为原来的对象。**
```python
import pickle data = ("胡桃", 2333, [1, 2, 3]) with open('sample_pickle.dat', 'wb') as f: try: pickle.dump(len(data), f) for item in data: pickle.dump(item, f) except: print('写文件异常')
with open('sample_pickle.dat','rb') as f: n = pickle.load(f) for i in range(n): x = pickle.load(f) print(x) ```python
```python import struct sn = struct.pack('if?', 123, 114.514, True) s = "胡桃我真的好喜欢你啊!"
with open('sample_struct.dat','wb') as f: f.write(sn) f.write(s.encode()) ```python
读取
```python with open('sample_struct.dat','rb') as f: sn = f.read(9) n, x, b1 = struct.unpack('if?', sn) print('n=',n,'x=',x, 'b1=', b1) s = f.read(9).decode() print('s=', s) ```python
写入
```python import shelve zhangsan = {'age':38,'sex':'Male','address':'SDIBT'} lisi = {'age':40,'sex':'Male','qq':'1234567','tel':'7654321'} with shelve.open('shelve_test.dat') as fp: fp['zhangsan'] = zhangsan fp['lisi'] = lisi for i in range(5): fp[str(i)] = str(i) ```python
读取
```python with shelve.open('shelve_test.dat') as fp: print(fp['zhangsan']) print(fp['zhangsan']['age']) print(fp['lisi']['qq']) print(fp['3']) ```python
结果
```python {'sex': 'Male','address': 'SDIBT','age': 38} 38 1234567 3 ```python
写入
```python import marshal x = [30, 5.0, [1, 2, 3], (4, 5, 6), {'a': 1, 'b': 2, 'c': 3}, {8, 9, 7}] with open('test.dat', 'wb') as fp: marshal.dump(len(x), fp) for item in x: marshal.dump(item,fp) ```python
读取
```python with open('test.dat','rb') as fp: n = marshal.load(fp) for i in range(n): print(marshal.load(fp)) ```python
结果
```python 30 5.0 [1, 2, 3] (4, 5, 6) {'a': 1, 'b': 2, 'c': 3} {8, 9, 7} ```python
```python import openpyxl from openpyxl import Workbook fn = r'f:\test.xlsx' wb = Workbook() ws = wb.create_sheet(title='你好,世界') ws['A1'] = '这是第一个单元格' ws['B1'] = 3.1415926 wb.save(fn) wb = openpyxl.load_workbook(fn) ws = wb.worksheets[1] print(ws['A1'].value) ws.merge_cells('F2:F3') ws['F2'] = "=sum(A2:E2)" for r in range(10,15): for c in range(3,8): ws.cell(row=r, column=c, value=r*c) wb.save(fn) ```python
```python from openpyxl import Workbook def main(txtFileName): new_XlsxFileName = txtFileName[:-3] + 'xlsx' wb = Workbook() ws = wb.worksheets[0] with open(txtFileName) as fp: for line in fp: line = line.strip().split(',') ws.append(line) wb.save(new_XlsxFileName) main('test.txt')
|