python 读取txt文件-python读写txt文件

本文介绍了Python中常见的文件操作方法,包括按行读取、一次性读取全部内容、按列表形式读取、追加写入等,并详细说明了seek、tell及flush方法的使用场景。

整理平常经常用到的文件对象方法:

f.readline() 逐行读取数据

方法一:

1 >>> f = open("/tmp/test.txt")2 >>>f.readline()3 "hello girl! "4 >>>f.readline()5 "hello boy! "6 >>>f.readline()7 "hello man!"8 >>>f.readline()9 ""

方法二:

1 >>> for i in open("/tmp/test.txt"):2 ... print i3 ...4 hello girl!

5 hello boy!

6 hello man!

7 f.readlines() 将文件内容以列表的形式存放8

9 >>> f = open("/tmp/test.txt")10 >>>f.readlines()11 ["hello girl! ", "hello boy! ", "hello man!"]12 >>> f.close()

f.next() 逐行读取数据,和f.readline() 相似,唯一不同的是,f.readline() 读取到最后如果没有数据会返回空,而f.next() 没读取到数据则会报错

1 >>> f = open("/tmp/test.txt")2 >>>f.readlines()3 ["hello girl! ", "hello boy! ", "hello man!"]4 >>>f.close()5 >>>

6 >>> f = open("/tmp/test.txt")7 >>>f.next()8 "hello girl! "9 >>>f.next()10 "hello boy! "11 >>>f.next()12 "hello man!"13 >>>f.next()14 Traceback (most recent call last):15 File "", line 1, in

16 StopIteration

f.writelines() 多行写入

1 >>> l = [" hello dear!"," hello son!"," hello baby! "]2 >>> f = open("/tmp/test.txt","a")3 >>>f.writelines(l)4 >>>f.close()5 [root@node1 python]#cat /tmp/test.txt

6 hello girl!

7 hello boy!

8 hello man!

9 hello dear!

10 hello son!

11 hello baby!

f.seek(偏移量,选项)

1 >>> f = open("/tmp/test.txt","r+")2 >>>f.readline()3 "hello girl! "4 >>>f.readline()5 "hello boy! "6 >>>f.readline()7 "hello man! "8 >>>f.readline()9 " "10 >>>f.close()11 >>> f = open("/tmp/test.txt","r+")12 >>>f.read()13 "hello girl! hello boy! hello man! "14 >>>f.readline()15 ""16 >>> f.close()

这个例子可以充分的解释前面使用r+这个模式的时候,为什么需要执行f.read()之后才能正常插入

f.seek(偏移量,选项)

(1)选项=0,表示将文件指针指向从文件头部到“偏移量”字节处

(2)选项=1,表示将文件指针指向从文件的当前位置,向后移动“偏移量”字节

(3)选项=2,表示将文件指针指向从文件的尾部,向前移动“偏移量”字节

偏移量:正数表示向右偏移,负数表示向左偏移

1 >>> f = open("/tmp/test.txt","r+")2 >>> f.seek(0,2)3 >>>f.readline()4 ""5 >>> f.seek(0,0)6 >>>f.readline()7 "hello girl! "8 >>>f.readline()9 "hello boy! "10 >>>f.readline()11 "hello man! "12 >>>f.readline()13 ""

f.flush() 将修改写入到文件中(无需关闭文件)

>>> f.write("hello python!")>>>f.flush()

hello girl!hello boy!hello man!hello python!

f.tell() 获取指针位置

1 >>> f = open("/tmp/test.txt")2 >>>f.readline()3 "hello girl! "4 >>>f.tell()5 12

6 >>>f.readline()7 "hello boy! "8 >>>f.tell()9 23

<think>我们正在处理用户的问题:如何用Python读取txt文件,并请求示例代码。根据引用[1]和引用[2]的内容,我们可以提供两种常见的读取txt文件的方法:逐行读取和一次性读取整个文件。我们将按照以下结构回答:1.介绍两种方法:逐行读取和一次性读取整个文件。2.分别给出示例代码,并解释代码的含义。3.提醒注意事项,如文件路径、编码、异常处理等。注意:用户的问题明确要求示例代码,因此我们将重点放在代码示例上。同时,根据引用内容,我们将提供两种方法的代码。由于引用中已经提供了示例代码,我们可以直接使用并稍作解释。另外,根据系统级指令,我们需要在回答中自然地添加引用标识。由于引用[1]和引用[2]都提到了读取txt文件的方法,我们可以在适当的地方添加引用。我们将使用中文回答。最后,根据指令,我们需要生成相关问题。在回答结束后,我们会生成几个相关问题。</think>### 如何使用Python读取txt文件Python读取txt文件主要使用内置的 `open()` 函数,以下是两种常用方法的示例代码和说明: #### 方法1:一次性读取整个文件内容 ```python # 指定文件路径(替换为你的实际路径) file_path = &#39;example.txt&#39; try: # 使用&#39;r&#39;模式打开文件(只读) with open(file_path, &#39;r&#39;, encoding=&#39;utf-8&#39;) as file: # 读取全部内容到字符串 content = file.read() print(content) except FileNotFoundError: print("文件不存在!") ``` - **`with open(...)`**:自动管理文件关闭,避免资源泄漏 - **`encoding=&#39;utf-8&#39;`**:指定编码格式(根据文件实际编码调整) - **`file.read()`**:返回包含文件所有内容的字符串[^1] #### 方法2:逐行读取文件 ```python file_path = &#39;example.txt&#39; try: with open(file_path, &#39;r&#39;, encoding=&#39;utf-8&#39;) as file: # 逐行迭代读取 for line in file: # 去除行尾换行符并处理 processed_line = line.strip() print(processed_line) except IOError as e: print(f"读取错误: {e}") ``` - **`for line in file`**:高效迭代每行内容,适合大文件 - **`line.strip()`**:移除行首尾空白符和换行符`\n` - 内存友好:每次只加载一行到内存[^2] #### 关键注意事项: 1. **路径格式**: - 绝对路径:`r&#39;C:\data\file.txt&#39;` (Windows) 或 `/home/user/file.txt` (Linux/Mac) - 相对路径:`&#39;data/file.txt&#39;`(相对于当前工作目录) 2. **异常处理**: - `FileNotFoundError`:文件不存在 - `UnicodeDecodeError`:编码不匹配(尝试`encoding=&#39;latin1&#39;`) 3. **模式选择**: ```python open(&#39;file.txt&#39;, &#39;r&#39;) # 只读(默认) open(&#39;file.txt&#39;, &#39;r+&#39;) # 读写 open(&#39;file.txt&#39;, &#39;a&#39;, encoding=&#39;utf-8&#39;) # 追加写入 ``` > 示例文件`example.txt`内容: > ``` > 第一行文本 > 第二行: 2023年数据 > 第三行: 3.14 > ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值