python读取txt文件,将文件中第一列显示出来

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hju22/article/details/85109333

文件:
在这里插入图片描述
代码:

try:
    file=open('food.txt',"r")     #以读模式打开文件
except FileNotFoundError:          #如果文件不存在,给提示
    print("file is not found")
else:
    contents=file.readlines()       #读取全部行
    for content in contents:       #显示一行
        print(content.split(',')[0])   #每行用逗号分隔后,取第一个元素

运行结果:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/hju22/article/details/85109333