Python提供了一种使用其内置功能与文件进行交互的直接方法。核心功能围绕 open()
函数,该功能以文件路径和模式为参数。让我们探索阅读和写作:
读取文件:
要读取文件,通常使用 open()
函数使用'r'模式(读取模式),然后使用 read> read> read> read> read> readline()
code> code> read/ read/<code> read/<code> read/<code> read/内容。
<code class="“" python>#打开一个用于阅读的文件try:with open('my_file.txt'r&quot'r&quord''r&quot'' end =;&quot&quot#end =&quot;&quot;预防额外的新线#将所有行读入列表file.seek(0)行= file.readlines()print()print(lines)除fileNotFoundError:print(print'file n of file; quot; quot; quot; quot'')例外as e:print(f&quord o print(f&quord o a a错误)(发生“出现”(发生):{e}使用</code>逐行读取逐行读取的<code>,<code> readlines()</code>将所有行读取到列表中。 <code>用打开(...)作为文件:</code>构造确保即使发生错误也会自动关闭文件。 <p> <strong>编写文件:</strong> </p> <p>写入文件中涉及以'w'(写入)模式打开其,'a'(append)模式,或'x'(x'x'(独家创建)模式。 <code> write()</code>方法将内容添加到文件中。</p> <pre class="brush:php;toolbar:false"> <code class="“" python> try:with open('my_new_file.txt.txt.txt'w&quord''打开(my_new_file.txt; a; a; a;文件,如果已经存在,则会失败。请记住要在适当的线路中包括新线字符(<code> \ n </code>)。 <h2> python中可用的不同文件模式用于文件I/O?</h2> <p> python's <code> open()</code> open()</p></code>打开读取文件。这是默认模式。如果文件不存在,则会发生错误。
可以将这些模式组合在一起。例如,'r b&quot'
在二进制模式下读取和写作的文件。
文件I/O操作i/o操作,例如遇到各种错误,例如不充分的文件,不充分的允许允许允许允许。强大的代码应优雅处理。最常见的方法是使用 try-except
块:
<code class="“" python> try:ling open('my_file.txt; r&quord'r&quot; “ w w” {e};)</code>
此示例捕获特定异常( fileNotFoundError
, permission> permissionError
, oserror
excep> decect> excect
以捕获任何其他潜在的问题。始终在可能的情况下有效处理错误。 读取和编写大型文件需要优化以避免记忆问题并提高性能。以下是一些最佳实践:
逐行迭代。对于大文件而言,这要高得多。
io.bufferedReader
和 io.bufferedwriter
类提供缓冲i/o,可以通过较大的disk Access in of disk访问来改进disk actext。进一步提高记忆效率。生成器会按需产生值,避免将整个文件加载到内存中。 mmap
(内存映射)。这将文件的一部分映射到内存,允许有效访问特定部分而无需加载整个文件。<pre class="brush:php;toolbar:false"> <code class="“" python>导入ioo导入io import mmap #chunking示例chunk_size = 1024 with open with open(grige_file.txt&quec quit fife n offile:ch;零件:休息#process块#... #memory映射示例,带有open('groom_file.txt'r b b b b&quot“ r b&quot”)作为f:mm = mm = mmap.mmap(f.fileno(f.fileno(),0)#0表示使用MM [pree> ofert offect off infe quastery pred] mm.m.cl/consemptign pred>在特定应用程序以及如何访问文件上。对于顺序处理,逐行迭代或使用缓冲I/O通常就足够了。对于随机访问,内存映射可能更合适。对于超出可用RAM的极大文件,请考虑使用专门的库,例如<code> dask </code>或<code> vaex </code>处理核心外计算。</code>
以上是如何在Python中读取和写文件?的详细内容。更多信息请关注PHP中文网其他相关文章!