1 open()函数
file = open('example.txt', 'r')
print(file.read())
file.close()
(1)整体读入,可以直接read()
(2)一定要记得关闭
2 with语句
with open('example.txt', 'r') as f:
for line in f:
print(line.strip())
(1)line.strip的意思是去掉换行符
(2)该种方法不需要close文件,会自动关闭。
(3)按行读入,适合需要按行处理数据时。
3 readlines()
with open('example.txt', 'r') as f:
lines = f.readlines()
for line in lines:
print(line.strip())
(1)整体读入,每行是列表
(2)对于需要读取特定列的时候使用方便,索引从0开始。最大行数用len()计算。
代码如下:
file = open('example.txt', 'r')
lines = file.readlines()
first_line = lines[0]
print(first_line)
file.close()
4 pandas库
import pandas as pd
df = pd.read_csv('example.txt', sep='\t')
print(df.head())
(1)需导入pandas库
(2)sep指定了字段的分隔符
(3)head()打印前5条数据
参考:
Python 读取txt文件|极客笔记 (deepinout.com)
标签:读取,python,file,print,line,txt,open,example From: https://blog.csdn.net/Luinee/article/details/137245764