md1999
md1999

Reputation: 19

Is there a function for extracting time of txt file using Python

How to extract time from txt file which contains 700 lines and each line has a specific time? using Python for example in my txt file:

14.999682   7.119120    13.02.2018 07:06:51
19.999625   7.119110    13.02.2018 07:06:56

Upvotes: 1

Views: 996

Answers (2)

BramAppel
BramAppel

Reputation: 1366

If you want to make use of all the elements in your source file, I would recommend to read it into a pandas DataFrame.

import pandas as pd

# read all data from the text file
# Since I do not know the separator whitespaces within the file I
# used a regex for any occurring white space
df = pd.read_csv('sourcefile.txt', sep=r'[\s]+', header=None)

# assign names to the columns
df.columns = ['A', 'B', 'Date', 'Time']

# your list
time_list = df['Time'].to_list()

Upvotes: 0

PirateNinjas
PirateNinjas

Reputation: 2096

This can be done pretty easily by reading in the file using readlines and then using the split method:

time_list = []
with open(your_filename) as f:
    for line in f.readlines():
        time_list.append(line.split()[3])

This will get your times in a list (time_list) which you can use to do whatever you need to do.

Upvotes: 3

Related Questions