python怎么读取txt文件

如题所述

如果要读取 txt 文件和 csv 文件的话,使用 pandas 模块很合适;

以下代码调试通过:

import pandas as pd

mydata_txt = pd.read_csv('lucia_test.txt', sep='\n', encoding='utf8')
print(mydata_txt)

运行效果:

温馨提示:答案为网友推荐,仅供参考
第1个回答  2018-08-04
是报错,还是得到的结果不对
如果是得到的结果不对,原因是你所有循环中都是对着a,b操作,这两个对象一直在改变,所以你得到的结果就是错误的本回答被网友采纳
第2个回答  2024-05-14
Python读取文本文件的步骤非常简单。以下是三种最常用读取txt文件的方法:
1、使用open()函数
#打开文件,mode参数指定打开方式('r'表示只读)
with open("file.txt","r")as f:
#读取文件内容
text=f.read()
2、使用for循环
with open("file.txt","r")as f:
#按行读取文件内容
for line in f:
#对每一行内容进行处理
print(line)
3、使用readlines()方法
with open("file.txt","r")as f:
#读取文件内容到一个列表中,每行为一个元素
lines=f.readlines()
4、示例代码
#使用open()函数读取整个文件:
with open("password.txt","r")as f:
passwords=f.read()
print(passwords)
#使用for循环按行读取文件
with open("data.txt","r")as f:
for line in f:
print(line.strip())
#使用readlines()方法读取文件到列表:
with open("employees.txt","r")as f:
employees=f.readlines()
for employee in employees:
print(employee.strip())