Hi I am trying to read data from a text file, line by line. However I am having problems with the output of the last line.

The text file I have created is:

position 50 10
line 50 0
line -50 0
line 0 -50

Here is my code:

f = open("temp.txt","r")

line = f.readline()
while line != "":
	line = line[:-1]
	print line
	data = split(line, " ")
	line = f.readline()

I get the following output:

position 50 10
line 50 0
line 0 50
line -50 90
line 0 -5

For some reason the last 0 keeps getting cut off.


I've also tried:

f = open("temp.txt","r")


for line in f:
	print line,
	data = split(line, " ")

This seems to give me the correct output but I don't want to print each line.

Try
line = line.strip() ## instead of line = line[:-1]
or make sure there is a return/newline in the last line of the file.

Try
line = line.strip() ## instead of line = line[:-1]
or make sure there is a return/newline in the last line of the file.

Thanks I'm silly I never checked for that. I had it working before but I edited the file afterwards and it stopped working.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.