Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the first n characters of a line from a text file?

I am trying to get the first 33 characters of a line from a text file. As an example, I have the following model:

The text file looks like this:

['1996/01/11', '00:14:36', '267', '18', '499', '571', '426', '0', '-64.3*', '-------', '-------', '272', 'Only', 'C3']
['1996/01/13', '22:08:30', '2020', '16', '290', '278', '303', '372', '2.8*', '-------', '-------', '266', 'Only', 'C3']

And I want to take only the first 33 characters of it.

I tried doing this:

with open(filename, 'r') as filehandle:
    current_line = 1
    for line in filehandle:
        if current_line > 4:
            words = line.split()
            print(str(words[0:33]) + "\n")
        current_line += 1

However, I did not succeed. Can you help me please?

I want to do this because I need the date, the time and also the first values in order to concatenate the date and the time into datetime and have the value separately.

like image 983
Ariadne R. Avatar asked Dec 30 '25 03:12

Ariadne R.


1 Answers

You can simply slice the array like that:

line[0:33]
like image 180
soMarios Avatar answered Jan 01 '26 19:01

soMarios