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

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

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

    35durant
    teamGSW

    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']

    使用strip()函数去掉每行结束的

    例如:

    1)

     for line in file.readlines():

          line=line.strip(' ')

    2)

    #读取 ip地址文件 写入 ip_address 列表
    ip_address = []
    with open('ip.txt', 'r') as f1:
    for ip in f1.readlines():
    if ip != None:
    # 从文件中读取行数据时,会带换行符,使用strip函数去掉 换行符后存入列表
    ip_address.append(ip.strip(" "))
    f1.close()

    strip()函数原型

    声明:s为字符串,rm为要删除的字符序列

    s.strip(rm)        删除s字符串中开头、结尾处,位于 rm删除序列的字符

    s.lstrip(rm)       删除s字符串中开头处,位于 rm删除序列的字符

    s.rstrip(rm)      删除s字符串中结尾处,位于 rm删除序列的字符

    注意:

    当rm为空时,默认删除空白符(包括' ', ' ',  ' ',  ' ')

     
  • 相关阅读:
    CodeForces 219D Choosing Capital for Treeland (树形DP)
    POJ 3162 Walking Race (树的直径,单调队列)
    POJ 2152 Fire (树形DP,经典)
    POJ 1741 Tree (树的分治,树的重心)
    POJ 1655 Balancing Act (树的重心,常规)
    HDU 2196 Computer (树形DP)
    HDU 1520 Anniversary party (树形DP,入门)
    寒门子弟
    JQuery选择器(转)
    (四)Web应用开发---系统架构图
  • 原文地址:https://www.cnblogs.com/Centwei/p/14425267.html
Copyright © 2011-2022 走看看