Why am I getting extra newline characters when reading a file in Python?

0
1
Asked By CodingNinja123 On

Hey everyone! I'm just starting to learn Python and I've hit a bit of a snag with reading text files. So, I've got a text file that I'm trying to read, and I'm ok with basic handling, but here's my question:

I executed some code to read from a text file starting at index 14, which I expected to read the character 'n' to the end. I saved that to a variable 'x'. Then, I read the file again starting from index 15, and to my surprise, I got an extra 'n' character in this second read. I thought I was starting at 'h' (the character at index 15) and not at the newline character!

Am I just not understanding how this works, or is Python being weird here? Here's the text in my file:

yoo sup CHATS.

how the phone lingings

Hi my FRIENDS?

And this is what I wrote in my code:

filo=open("12b7.txt")
print(filo.read())
filo.seek(14)
x=filo.read()
print(x)
filo.seek(15)
y=filo.read()
print(y)
if x==y:
print("true")
filo.close()

So yeah, I'm confused. Help a fellow newbie out!

2 Answers

Answered By CuriousCoder88 On

Yep, Microsoft's handling of newlines is a bit tricky! When Python reads files, it translates 'rn' to just 'n'. If you're seeking to read from the middle of a newline, you'll end up getting an extra character as Python standardizes it. It's kind of a quirk of how it works on different platforms. Keep experimenting, and you’ll get the hang of it!

CodingNinja123 -

Oh, I appreciate you explaining that! I'm learning so much from just these little interactions. Thanks!

Answered By TechSaver99 On

It looks like you're running into an issue with newlines in your text file. If you're on Windows, newlines are usually represented as two characters: 'rn'. When you read the file, Python might be treating those differently depending on your position in the text. Make sure to check if the character at index 14 is actually 'n' or potentially 'r'! That could explain the extra newline you're seeing. Let me know if that clears it up!

LearningPython42 -

Thanks a ton for the tip! I didn’t realize that about Windows, makes a lot more sense now. Gonna try that and see what happens!

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.