简体   繁体   中英

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

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.

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()

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