0
点赞
收藏
分享

微信扫一扫

springboot使用WebSocket

cnlinkchina 2024-08-14 阅读 37

博客目录

一.需求背景

1.文本文件

电影.txt 的内容如下

2.需求背景

需要按不同的方式读取 txt 中的内容
在这里插入图片描述

二.实现代码

要读取一个文本文件,可以使用 Python 的内置函数 open()。你可以通过不同的模式打开文件来读取其内容。下面是几个常见的读取文件的方法示例:

1. 读取整个文件

如果你要读取整个文件的内容,可以使用 read() 方法:

# 打开文件并读取内容
with open('电影.txt', 'r', encoding='utf-8') as file:
    content = file.read()

# 打印文件内容
print(content)

2. 逐行读取文件

如果文件非常大,你可以逐行读取,以节省内存:

# 打开文件并逐行读取内容
with open('电影.txt', 'r', encoding='utf-8') as file:
    for line in file:
        print(line.strip())  # strip() 去掉行尾的换行符

3. 读取文件的前几行

如果你只需要读取文件的前几行,可以这样做:

# 打开文件并读取前几行
with open('电影.txt', 'r', encoding='utf-8') as file:
    lines = [next(file) for _ in range(5)]  # 读取前5行

# 打印前几行
for line in lines:
    print(line.strip())

4. 读取文件为列表

将文件的每一行读入一个列表:

# 打开文件并读取所有行到列表
with open('电影.txt', 'r', encoding='utf-8') as file:
    lines = file.readlines()

# 打印文件内容
for line in lines:
    print(line.strip())

5. 读取文件并处理异常

在处理文件时,处理异常是一个好习惯,可以确保你的代码在文件未找到或其他问题时不会崩溃:

try:
    with open('电影.txt', 'r', encoding='utf-8') as file:
        content = file.read()
        print(content)
except FileNotFoundError:
    print("The file was not found.")
except IOError:
    print("An error occurred while reading the file.")

6. 文件编码

指定 encoding='utf-8' 是一个好的做法,尤其是当你处理包含非 ASCII 字符的文件时。根据文件的实际编码方式,可能需要使用其他编码,如 'utf-16''iso-8859-1'
在这里插入图片描述

总结

  • open(): 用于打开文件,返回一个文件对象。
  • read(): 读取文件的全部内容。
  • readlines(): 读取文件的所有行到一个列表。
  • 逐行读取: 遍历文件对象,逐行读取。
  • 异常处理: 处理文件打开和读取中的潜在问题。
举报

相关推荐

0 条评论