[Python] Python strip() and readlines()

Discussão em 'Python' iniciado por Stack, Setembro 15, 2024.

  1. Stack

    Stack Membro Participativo

    I have a code that I am trying to run which will compare a value from a csv file to a threshold that I have set within the py file.

    My csv file has an output similar to below, but with 1030 lines

    -46.62

    -47.42

    -47.36

    -47.27

    -47.36

    -47.24

    -47.24

    -47.03

    -47.12


    Note: there are no lines between the values but there is a single space before them.

    My first attempt was with this code:

    file_in5 = open('710_edited_capture.csv', 'r')

    line5=file_in5.readlines()

    a=line5[102]

    b=line5[307]

    c=line5[512]

    d=line5[717]

    e=line5[922]

    print[a]

    print

    print[c]

    print[d]

    print[e]


    which gave the output of:

    [' -44.94\n']

    [' -45.06\n']

    [' -45.09\n']

    [' -45.63\n']

    [' -45.92\n']


    My first thought was to use .strip() to remove the space and the \n but this is not supported in lists and returns the error:

    Traceback (most recent call last):
    File "/root/test.py", line 101, in <module>

    line5=line5.strip()
    AttributeError: 'list' object has no attribute 'strip'


    My next code below:

    for line5 in file_in5:

    line5=line5.strip()

    line5=file_in5.readlines()

    a=line5[102]

    b=line5[307]

    c=line5[512]

    d=line5[717]

    e=line5[922]

    print[a]

    print

    print[c]

    print[d]

    print[e]


    Returns another error:

    Traceback (most recent call last):
    File "/root/test.py", line 91, in <module>

    line5=file_in5.readlines()
    ValueError: Mixing iteration and read methods would lose data


    What is the most efficient way to read in just 5 specific lines without any spaces or \n, and then be able to use them in subsequent calculations such as:

    if a>threshold and a>b and a>c and a>d and a>e:
    print ('a is highest and within limit')
    CF=a

    Continue reading...

Compartilhe esta Página