Python文件IO

Python文件IO

有如下文本内容,文件路径为D:\temp,文件名称为lyric.txt,

line1 Look ! 
line2 If U had one shot
line3 One opportunity
line4 To seize everything U ever wanted
line5 One moment
line6 Would U capture it ? 
line7 Or just let it slip

  

  1. 逐行读取,并输出
    #coding=utf-8 
    import os
    file_path = r'D:\temp'
    file_name = 'lyric.txt'
    #拼接文件路径与名称
    file_URI = os.path.join(file_path,file_name)
    print("file_URI--  " + file_URI)
    fd = open(file_URI, mode='r')
    #逐行读取文件内容
    for line in fd:
        #输出每行内容,每行行尾有换行符号
        print(line)

    输出结果,单独输出每行,包含此行的换行符: 

  2. file_URI--  D:\temp\lyric.txt
    line1 Look ! 
    
    line2 If U had one shot
    
    line3 One opportunity
    
    line4 To seize everything U ever wanted
    
    line5 One moment
    
    line6 Would U capture it ? 
    
    line7 Or just let it slip



  3. read(),读取全部内容
    #coding=utf-8 
    import os
    file_path = r'D:\temp'
    file_name = 'lyric.txt'
    file_URI = os.path.join(file_path,file_name)
    print("file_URI--  " + file_URI)
    fd = open(file_URI, mode='r')
    content = fd.read()
    print(content)

    输出结果

    file_URI--  D:\temp\lyric.txt
    line1 Look ! 
    line2 If U had one shot
    line3 One opportunity
    line4 To seize everything U ever wanted
    line5 One moment
    line6 Would U capture it ? 
    line7 Or just let it slip

     

  4. readlines(),读取全部内容,返回每行内容作为元素的列表
    #coding=utf-8 
    import os
    file_path = r'D:\temp'
    file_name = 'lyric.txt'
    file_URI = os.path.join(file_path,file_name)
    print("file_URI--  " + file_URI)
    fd = open(file_URI, mode='r')
    content_list = fd.readlines()
    print(content_list)

    输出结果

    file_URI--  D:\temp\lyric.txt
    ['line1 Look ! \n', 'line2 If U had one shot\n', 'line3 One opportunity\n', 'line4 To seize everything U ever wanted\n', 'line5 One moment\n', 'line6 Would U capture it ? \n', 'line7 Or just let it slip']

     

转载于:https://www.cnblogs.com/AlexBai326/p/4088537.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值