温馨提示×

python文本文件读取的方法有哪些

小亿
85
2024-05-27 19:48:15
栏目: 编程语言

Python中文本文件读取的方法有以下几种:

  1. 使用open函数打开文件并读取内容:
file = open('file.txt', 'r')
content = file.read()
file.close()
  1. 使用with语句自动关闭文件:
with open('file.txt', 'r') as file:
    content = file.read()
  1. 逐行读取文件内容:
with open('file.txt', 'r') as file:
    for line in file:
        print(line)
  1. 读取指定行数的内容:
with open('file.txt', 'r') as file:
    lines = file.readlines()[:5]  # 读取前5行内容
    for line in lines:
        print(line)
  1. 读取文件中的单词或者特定字符:
with open('file.txt', 'r') as file:
    content = file.read()
    words = content.split()  # 分割成单词列表
    for word in words:
        print(word)

这些方法可以根据具体的需求选择使用,可以满足大部分的文件读取操作。

0