-1

This is my code for finding the speed of cars, when it runs it leaves a line between the printed distance(dist) and the speed

I have looked at how to remove the \n from the end but all of them that I've seen and tried have made it print out the word dist and not the number in the variable:

for line in open ('data.txt','r'):
    z,x,y,dist=line.rsplit(",")
    print(z)
    print(x)
    print(y)
    print(dist)
    speed = int(dist)/(int(y)-int(x))
    print(speed)
poke
  • 369,085
  • 72
  • 557
  • 602

1 Answers1

1

Lines read from a file include the line separators. You can use str.rstrip() to remove it:

z, x, y, dist = line.rstrip().split(',')

This will remove all whitespace (spaces, tabs, line separators, etc.) from the end of the line before splitting the line by comma.

Your file format is perhaps more easily read with the csv module:

import csv

with open('data.txt', newline='') as csvfile:
    reader = csv.reader(csvfile)
    for row in reader:
        z, x, y, dist = map(int, row)
        print(z)
        print(x)
        print(y)
        print(dist)
        speed = dist / (y - x)
        print(speed)
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343