简体   繁体   中英

How to extract specific data from a text file in python

I am trying to extract specific data out of a text file to use it in another function. I already looked this up and found something but it doesn't work although it seems like it should work. Is there anything I do wrong or is there a better way to do this? I am basically trying to extract the first column of data in the text file the "distances", without the km of course.

This is the text file:

Distances              Times                    Dates               Total distance & time
00 km                  00:00:00 h               0000-00-00            00 km ; 00:00:00 h
28 km                  01:30:21 h               2020-3-2              28 km ; 01:30:21 h
50 km                  02:12:18 h               2020-4-8              78 km ; 

This is the code:

all_distances = []

with open("Bike rides.txt", "r") as f:
   lines = f.readlines()

   for l in lines[1:]:
       all_distances.append(l.split()[0])

print(all_distances)

The error I get is this:

IndexError: list index out of range

Considering you have whitespace delimiters, you can separate the columns using string.split() method. Below is an example of its application.

column = 0  # First column
with open("data.txt") as file:
  data = file.readlines()
columns = list(map(lambda x: x.strip().split()[column], data))

try this one:

#!/usr/bin/env python3
all_distances = []

for l in open ( "rides.txt" ).readlines () [ 1: ]:
    l = l.split ( " " ) [ 0 ]
    all_distances.append ( l )


print(all_distances)

The error i get is this: "IndexError: list index out of range" This suggest problem with blank line(s), so .split() give empty list, to ignore such lines in place:

all_distances.append(l.split()[0])

do:

splitted = l.split()
if splitted:
    all_distances.append(splitted[0])

Explanation: in python empty lists are considersing false-y and non-empty truth-y, thus code inside if block will execute if list has at least one element.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM