Python全栈之路系列之文件操作

skymysky 7年前
   <p>Python可以对文件进行查看、创建等功能,可以对文件内容进行添加、修改、删除,且所使用到的函数在Python3.5.x为 open ,在Python2.7.x同时支持 file 和 open ,但是在3.5.x系列移除了 file 函数。</p>    <h2>Python文件打开方式</h2>    <pre>  <code class="language-python">文件句柄 = open('文件路径','打开模式')</code></pre>    <p>Ps:文件句柄相当于于变量名,文件路径可以写为绝对路径也可以写为相对路径。</p>    <h2>Python打开文件的模式</h2>    <p>基本的模式</p>    <table>     <thead>      <tr>       <th>模式</th>       <th>说明</th>       <th>注意事项</th>      </tr>     </thead>     <tbody>      <tr>       <td>r</td>       <td>只读模式</td>       <td>文件必须存在</td>      </tr>      <tr>       <td>w</td>       <td>只写模式</td>       <td>文件不存在则创建文件,文件存在则清空文件内容</td>      </tr>      <tr>       <td>x</td>       <td>只写模式</td>       <td>文件不可读,文件不存在则创建,存在则报错</td>      </tr>      <tr>       <td>a</td>       <td>追加模式</td>       <td>文件不存在创建文件,文件存在则在文件末尾添加内容</td>      </tr>     </tbody>    </table>    <p>带 + 的模式</p>    <table>     <thead>      <tr>       <th>模式</th>       <th>说明</th>      </tr>     </thead>     <tbody>      <tr>       <td>r+</td>       <td>读写</td>      </tr>      <tr>       <td>w+</td>       <td>写读</td>      </tr>      <tr>       <td>x+</td>       <td>写读</td>      </tr>      <tr>       <td>a+</td>       <td>写读</td>      </tr>     </tbody>    </table>    <p>带 b 的模式</p>    <table>     <thead>      <tr>       <th>模式</th>       <th>说明</th>      </tr>     </thead>     <tbody>      <tr>       <td>rb</td>       <td>二进制读模式</td>      </tr>      <tr>       <td>wb</td>       <td>二进制写模式</td>      </tr>      <tr>       <td>xb</td>       <td>二进制只写模式</td>      </tr>      <tr>       <td>ab</td>       <td>二进制追加模式</td>      </tr>     </tbody>    </table>    <p>提示:以b方式打开时,读取到的内容是字节类型,写入时也需要提供字节类型</p>    <p>带 + 带 b 的模式</p>    <table>     <thead>      <tr>       <th>模式</th>       <th>说明</th>      </tr>     </thead>     <tbody>      <tr>       <td>rb+</td>       <td>二进制读写模式</td>      </tr>      <tr>       <td>wb+</td>       <td>二进制读写模式</td>      </tr>      <tr>       <td>xb+</td>       <td>二进制只写模式</td>      </tr>      <tr>       <td>ab+</td>       <td>二进制读写模式</td>      </tr>     </tbody>    </table>    <h2>Python文件读取方式</h2>    <table>     <thead>      <tr>       <th>模式</th>       <th>说明</th>      </tr>     </thead>     <tbody>      <tr>       <td>read([size])</td>       <td>读取文件全部内容,如果设置了size,那么久读取size字节</td>      </tr>      <tr>       <td>readline([size])</td>       <td>一行一行的读取</td>      </tr>      <tr>       <td>readlines()</td>       <td>读取到的每一行内容作为列表中的一个元素</td>      </tr>     </tbody>    </table>    <p>测试的文件名是 hello.tx" ,文件内容为:</p>    <pre>  <code class="language-python">Hello Word!  123  abc  456  abc  789  abc</code></pre>    <p>read</p>    <p>代码:</p>    <pre>  <code class="language-python"># 以只读的方式打开文件hello.txt  f = open("hello.txt","r")  # 读取文件内容赋值给变量c  c = f.read()  # 关闭文件  f.close()  # 输出c的值  print(c)</code></pre>    <p>输出结果:</p>    <pre>  <code class="language-python">C:\Python35\python.exe F:/Python_code/sublime/Day06/file.py  Hello Word!  123  abc  456  abc  789  abc</code></pre>    <p>readline</p>    <p>代码:</p>    <pre>  <code class="language-python"># 以只读模式打开文件hello.txt  f = open("hello.txt","r")  # 读取第一行  c1 = f.readline()  # 读取第二行  c2 = f.readline()  # 读取第三行  c3 = f.readline()  # 关闭文件  f.close()  # 输出读取文件第一行内容  print(c1)  # 输出读取文件第二行内容  print(c2)  # 输出读取文件第三行内容  print(c3)</code></pre>    <p>输出结果:</p>    <pre>  <code class="language-python">C:\Python35\python.exe F:/Python_code/sublime/Day06/file.py  Hello Word!    123    abc</code></pre>    <p>readlines</p>    <pre>  <code class="language-python"># 以只读的方式打开文件hello.txt  f = open("hello.txt","r")  # 将文件所有内容赋值给c  c = f.readlines()  # 查看数据类型  print(type(c))  # 关闭文件  f.close()  # 遍历输出文件内容  for n in c:      print(n)</code></pre>    <p>结果</p>    <pre>  <code class="language-python">C:\Python35\python.exe F:/Python_code/sublime/Day06/file.py  # 输出的数据类型  <class 'list'>  Hello Word!    123    abc    456    abc    789    abc</code></pre>    <h2>Python文件写入方式</h2>    <table>     <thead>      <tr>       <th>方法</th>       <th>说明</th>      </tr>     </thead>     <tbody>      <tr>       <td>write(str)</td>       <td>将字符串写入文件</td>      </tr>      <tr>       <td>writelines(sequence or strings)</td>       <td>写多行到文件,参数可以是一个可迭代的对象,列表、元组等</td>      </tr>     </tbody>    </table>    <p>write</p>    <p>代码:</p>    <pre>  <code class="language-python"># 以只读的模式打开文件write.txt,没有则创建,有则覆盖内容  file = open("write.txt","w")  # 在文件内容中写入字符串test write  file.write("test write")  # 关闭文件  file.close()</code></pre>    <p>write.txt 文件内容为:</p>    <pre>  <code class="language-python">test write</code></pre>    <p>writelines</p>    <p>代码:</p>    <pre>  <code class="language-python"># 以只读模式打开一个不存在的文件wr_lines.txt  f = open("wr_lines.txt","w",encoding="utf-8")  # 写入一个列表  f.writelines(["11","22","33"])  # 关闭文件  f.close()</code></pre>    <p>wr_lines.txt 文件内容:</p>    <h2>Python文件操作所提供的方法</h2>    <p>close(self):</p>    <p>关闭已经打开的文件</p>    <pre>  <code class="language-python">f.close()</code></pre>    <p>fileno(self):</p>    <p>文件描述符</p>    <pre>  <code class="language-python">f = open("hello.txt","r")  ret = f.fileno()  f.close()  print(ret)</code></pre>    <p>执行结果:</p>    <p>flush(self):</p>    <p>刷新缓冲区的内容到硬盘中</p>    <pre>  <code class="language-python">f.flush()</code></pre>    <p>isatty(self):</p>    <p>判断文件是否是tty设备,如果是tty设备则返回 True ,否则返回 False</p>    <pre>  <code class="language-python">f = open("hello.txt","r")  ret = f.isatty()  f.close()  print(ret)</code></pre>    <p>返回结果:</p>    <pre>  <code class="language-python">C:\Python35\python.exe F:/Python_code/sublime/Day06/file.py  False</code></pre>    <p>readable(self):</p>    <p>是否可读,如果可读返回 True ,否则返回 False</p>    <pre>  <code class="language-python">f = open("hello.txt","r")  ret = f.readable()  f.close()  print(ret)</code></pre>    <p>返回结果:</p>    <pre>  <code class="language-python">C:\Python35\python.exe F:/Python_code/sublime/Day06/file.py  True</code></pre>    <p>readline(self, limit=-1):</p>    <p>每次仅读取一行数据</p>    <pre>  <code class="language-python">f = open("hello.txt","r")  print(f.readline())  print(f.readline())  f.close()</code></pre>    <p>返回结果:</p>    <pre>  <code class="language-python">C:\Python35\python.exe F:/Python_code/sublime/Day06/file.py  Hello Word!    123</code></pre>    <p>readlines(self, hint=-1):</p>    <p>把每一行内容当作列表中的一个元素</p>    <pre>  <code class="language-python">f = open("hello.txt","r")  print(f.readlines())  f.close()</code></pre>    <p>返回结果:</p>    <pre>  <code class="language-python">C:\Python35\python.exe F:/Python_code/sublime/Day06/file.py  ['Hello Word!\n', '123\n', 'abc\n', '456\n', 'abc\n', '789\n', 'abc']</code></pre>    <ul>     <li> <p>tell(self):</p> </li>    </ul>    <p>获取指针位置</p>    <pre>  <code class="language-python">f = open("hello.txt","r")  print(f.tell())  f.close()</code></pre>    <p>返回结果:</p>    <pre>  <code class="language-python">C:\Python35\python.exe F:/Python_code/sublime/Day06/file.py  0</code></pre>    <p>seek(self, offset, whence=io.SEEK_SET):</p>    <p>指定文件中指针位置</p>    <pre>  <code class="language-python">f = open("hello.txt","r")  print(f.tell())  f.seek(3)  print(f.tell())  f.close()</code></pre>    <p>执行结果</p>    <pre>  <code class="language-python">C:\Python35\python.exe F:/Python_code/sublime/Day06/file.py  0  3</code></pre>    <p>seekable(self):</p>    <p>指针是否可操作</p>    <pre>  <code class="language-python">f = open("hello.txt","r")  print(f.seekable())  f.close()</code></pre>    <p>执行结果</p>    <pre>  <code class="language-python">C:\Python35\python.exe F:/Python_code/sublime/Day06/file.py  True</code></pre>    <p>writable(self):</p>    <p>是否可写</p>    <pre>  <code class="language-python">f = open("hello.txt","r")  print(f.writable())  f.close()</code></pre>    <p>执行结果</p>    <pre>  <code class="language-python">C:\Python35\python.exe F:/Python_code/sublime/Day06/file.py  False</code></pre>    <p>writelines(self, lines):</p>    <p>写入文件的字符串序列,序列可以是任何迭代的对象字符串生产,通常是一个 字符串列表 。</p>    <pre>  <code class="language-python">f = open("wr_lines.txt","w")  f.writelines(["11","22","33"])  f.close()</code></pre>    <p>执行结果</p>    <p>read(self, n=None):</p>    <p>读取指定字节数据,后面不加参数默认读取全部</p>    <pre>  <code class="language-python">f = open("wr_lines.txt","r")  print(f.read(3))  f.seek(0)  print(f.read())  f.close()</code></pre>    <p>执行结果</p>    <pre>  <code class="language-python">C:\Python35\python.exe F:/Python_code/sublime/Day06/file.py  112  112233</code></pre>    <p>write(self, s):</p>    <p>往文件里面写内容</p>    <pre>  <code class="language-python">f = open("wr_lines.txt","w")  f.write("abcabcabc")  f.close()</code></pre>    <p>文件内容</p>    <pre>  <code class="language-python">abcabcabc</code></pre>    <h2>同时打开多个文件</h2>    <p>为了避免打开文件后忘记关闭,可以通过管理上下文,即:</p>    <pre>  <code class="language-python">with open('log','r') as f:   代码块</code></pre>    <p>如此方式,当with代码块执行完毕时,内部会自动关闭并释放文件资源。</p>    <p>在Python 2.7 及以后,with又支持同时对多个文件的上下文进行管理,即:</p>    <pre>  <code class="language-python">with open('log1') as obj1, open('log2') as obj2:      pass</code></pre>    <p><a href="/misc/goto?guid=4959735939091507478" rel="nofollow,noindex">原文链接</a></p>    <p> </p>