zoukankan      html  css  js  c++  java
  • Python 三种读文件方法read(), readline(), readlines()及去掉换行符

    Python 三种读文件方法read(), readline(), readlines()及去掉换行符

    首先, 让我们看下数据demo.txt, 就两行数据.

    35durant
    teamGSW12
    

    1. read()

    with open("demo.txt", "r") as f:
        data = f.read()
        print(data)
        print(type(data))
    
    output[1]:
    35durant
    teamGSW
    

    这种方法直接将所有的数据一次性读取出来, data的数据类型是一个字符串.

    2. readline()

    with open("demo.txt", "r") as f:
        data = f.readline()
        print(data)
        print(type(data))
    
    output[1]:
    35durant
    
    <class 'str'>
    

    该方法读取的是一行内容, 然后是带换行符的, 所有会有空行, 后续会说明如何去掉换行符” ”.

    3. readlines()

    with open("demo.txt", "r") as f:
        data = f.readlines()
        print(data)
        print(type(data))
    
    output[1]:
    ['35durant
    ', 'teamGSW']
    <class 'list'>
    

    这种方法返回的是一个列表, 注意换行符是包含在字符串的内容中.

    接下来说明, 如何在读取文本文件时去掉字符串中的换行符: “ ”.
    这里以readlines()方法返回的list与read()方法返回的str为例, 分别进行说明.

    方法1: 基于list的索引操作

    with open("demo.txt", "r") as f:
        data = f.readlines()
        print(data)
        a = data[0][:-1]
        b = data[1]
        print(a, b)
    
    output[1]:
    ['35durant
    ', 'teamGSW']
    35durant teamGSW
    

    方法2: 基于str的splitlines()方法

    with open("demo.txt", "r") as f:
        data = f.read().splitlines()
        print(data)
    
    output[1]: 
    ['35durant', 'teamGSW']
    
  • 相关阅读:
    MySQL数据类型2
    MySQL数据类型1
    powerdesigner使用之——从“概念模型”到“物理模型”
    javascript中click和onclick的区别
    eclipse将javaSE项目导出成可执行jar包
    配置SQLServer,允许远程连接
    VirtualBox虚拟机中安装XP系统
    fastjson 的使用总结
    idea前端页面不刷新----springboot
    后台可以用layui快速开发
  • 原文地址:https://www.cnblogs.com/demiao/p/12712509.html
Copyright © 2011-2022 走看看