`n 如何在Python中读取和写入文件?

如何在Python中读取和写入文件?

Clock Icon 发布时间:2026/8/12 18:08  · 

NET/" style="text-decoration: none; color: inherit;" title="Python">Python中,读取和写入文件是常见的操作,通常可分为几个步骤。NET/" style="text-decoration: none; color: inherit;" title="Python">Python通过内建的`open()`函数来处理文件。需要指定文件的路径和打开模式。模式包括读取('r')、写入('w')、附加('a')、以及读取和写入('r+')等选项。
读取文件通常使用`open()`函数结合读取方法。使用`read()`可以一次性读取整个文件内容,使用`readline()`可以逐行读取,而使用`readlines()`则会将所有行读取到一个列表中。例如,打开文件读取内容的代码如下:
```NET/" style="text-decoration: none; color: inherit;" title="Python">Pythonwith open('filename.txt', 'r') as file: content = file.read()```使用`with`语句可以确保在完成后自动关闭文件。例如,以上代码将文件的内容存储在变量`content`中。
写入文件的操作也相似。在写入时,使用`open()`函数需要选择合适的模式。如果需要创建新文件或覆盖已经存在的,使用`'w'`模式。如果希望在文件末尾添加内容,使用`'a'`模式。例如,写入文件的代码如下:
```NET/" style="text-decoration: none; color: inherit;" title="Python">Pythonwith open('filename.txt', 'w') as file: file.write('Hello, World!')```这样的代码会将“Hello, World!”写入指定的文件中。
对于更复杂的文件操作,如处理CSV文件,NET/" style="text-decoration: none; color: inherit;" title="Python">Python提供了`csv`模块。这个模块可以方便地读取和写入以逗号分隔的数据。通过使用`csv.reader`和`csv.writer`,可以直接处理表格格式的数据。例如,读取CSV文件的基本示例:
```NET/" style="text-decoration: none; color: inherit;" title="Python">Pythonimport csvwith open('data.csv', 'r') as file: reader = csv.reader(file) for row in reader: print(row)```写入CSV文件的过程同样简单。
在处理文件时需注意异常处理。有时文件不存在或没有权限打开文件,这会引发异常。通过`try-except`语句可以捕获和处理这些异常,确保程序的稳定运行。示例如下:
```NET/" style="text-decoration: none; color: inherit;" title="Python">Pythontry: with open('filename.txt', 'r') as file: content = file.read()except FileNotFoundError: print("文件未找到!")except PermissionError: print("没有权限访问该文件!")```使用异常处理能够有效避免程序崩溃,提高健壮性。
文件读取和写入是NET/" style="text-decoration: none; color: inherit;" title="Python">Python编程中的基本技能。通过掌握这些技巧,可以方便地进行数据处理、存储和分析。随着对文件操作的理解加深,可以尝试更高级的功能,比如文件编码、文件指针操作等。

推荐文章

热门文章