热线电话:13121318867

登录
2019-03-04 阅读量: 762
python读取文件的方法有哪些?

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

答: 文件读取方法如下:

Python读取文件示例

# test01.txt 文件内容如下
1 2 3
4 5 6
7 8 9

# 读取文件全部内容
fname = "D:\\test01.txt" #确保D盘下有test.txt文件
infile = open(fname,"r")
data = infile.read()
# 上述两条代码也可合并成:data = open(fname,"r").read() #建议分开写
print(data)
# 输出结果
1 2 3
4 5 6
7 8 9

# 遍历读取文件全部内容
infile = open(fname,"r")
for line in infile:
print(line)
# 输出结果
1 2 3
4 5 6
7 8 9

# 读取文件前n行内容
fname = "D:\\test01.txt"
infile = open(fname,"r")
for i in range(2): #读取文件前几行
data = infile.readline()
print(data)
# 输出结果
1 2 3
4 5 6

# 从第2行开始读取文件内容(多用于去除表头)
fname = "D:\\tes01.txt"
infile = open(fname,"r")
infile.readline() #去除表头
data = infile.readlines() #以列表方式读取
print(data)
# 输出结果
4 5 6
7 8 9
0.0000
3
关注作者
收藏
评论(0)

发表评论

暂无数据
推荐帖子