[Tutor] Python text file read/compare

dn PythonList at DancesWithMice.info
Thu Sep 29 17:47:13 EDT 2022


Welcome!

On 30/09/2022 07.09, samira khoda wrote:
> Hello
> 
> I am very new to python programming. I actually just finished my course
> provided by my employer and now practicing on some data processing and I
> need some direction to solve the issue I have. Any help would be
> appreciated.

Which course?


> I am trying to create a loop that reads the file line by line and compares
> the last timestamp to the current one in my data to find the line number
> where to split the files. Then do another loop that writes lines to a new
> file based on those line numbers.

There's more than one task, or stage, to this.

Recommendation: split the problem into separate, smaller, problems -
then solve each, one at a time...


> Below is the snapshot of the data. Basically I need to find where the
> timestamps jump down to zero or the lowest number so I can split the file.
> For your information the timestamps are in milliseconds on the last column.
> 
> [image: image.png]

Unfortunately, this list will not carry graphics-files. Please
copy-paste (if it is short) - probably only need a few sample-lines to
give the correct impression.


> *And below is the code I wrote but nothing came out of it. Not even a new
> text file(s). I am sure there is definitely something wrong with this. I
> have a very hard time to figure this out.*

To have something "come out", or be able to 'see' what's happening (in a
routine of this size), add some print() calls.


> # op stands for output
> # opf stands for output file
> 
> with open('hfx-test-.txt') as kyk:
>     op=''
>     start=0
>     count=1
>     for x in kyk.read().split("\n"):

What does x look-like at this point?

>         if(x=='0'):

What is the intent of this condition?


>             if (start==1):

Why initiate the output file at this point (and not earlier)?
- this is complicated!
- there may be a good reason, but nothing was mentioned in the
specification (above)...


>                 with open(str(count)+ '.txt', 'w') as opf:
>                     opf.write(op)
>                     opf.close()
>                     op=''
>                     count+=1

At the start (of your work), ignore the output-stage, and replace it
with one or more print() calls ("mock" the output-file). What is shown?


>         else:
>             start=1
> 
>     else:
>         if(op==''):
> 
>           op = x
> 
>         else:
>             op= op+ '\n' + x
> 
> kyk.close()

Once the input-file processing is confirmed, how does this code extract
the timestamp?

How can this stage of the solution be seen/proven?
-- 
Regards,
=dn


More information about the Tutor mailing list