Home > Blockchain >  Python don't recognize "\n" when try to write in txt file
Python don't recognize "\n" when try to write in txt file

Time:04-30

Just start to learn python, I'm trying to write a file like this:

line1
line2
line3
line4
line5
line6
line7

this is my code:

with open("test.txt","w") as fp:
for num in range(1,8):
    x= str(num)
    fp.write("line" x)
    fp.write("\n")

with open("test.txt","r") as fp:
print(fp.readlines())

and this is the outcome :

['line1\n', 'line2\n', 'line3\n', 'line4\n', 'line5\n', 'line6\n', 'line7\n']

the "\n" did turn orange which make me think it should work but it does not does anyone know why python did not recognize the "\n" ?

https://img.codepudding.com/202204/6caf49c7c52e43ecaf4d48dbe6c0d435.jpg

CodePudding user response:

i think this is what you want

with open("test.txt","w") as fp:
        for num in range(1,8):
                x= str(num)
                fp.write("line" x)
                fp.write("\n")

with open("test.txt","r") as fp:
        print(fp.read())

readlines returns a list good luck!

CodePudding user response:

Python objects decide how they are to be printed using the __str__ and __repr__ "magic" methods. The "str" form is intended to be what the author thinks is the normal view of an object, where the "repr" is a more descriptive technical view.

The print function takes the "str" form of the things its going to print. If you did

with open("test.txt","r") as fp:
    print(fp.read())

read returns a string and the printed string would contain newlines. These are non-display characters that advance you to the next line. This would display the text the way you expect.

But you did print(fp.readlines()). readlines returns a list. A list is different. print calls its __str__ method, but the list turns around and gets the "repr" of its contained objects.

So now we are dealing with the "repr" of string. In this case, python displays non-displayable characters like newlines and tabs. How that's done is with the backslash character, which is treated as an escape in python literals. So "\n" is the single newline character, not a backslash and "n".

The "repr" of a string is the string literal you would use to recreate the string in a python program. Its convenient for copy / paste.

foo = 'line1\n'
print(foo)

would print the newline itself.

CodePudding user response:

fp.write() is doing exactly what you want. If you open the file in a text editor, you will see the content as:

line1
line2
line3
...

The \n you're seeing at the end of each line is caused by fp.readLines(). This function does not remove new-line characters from the end of each line when reading them from the file.

According to the documentation:

f.readline() reads a single line from the file; a newline character (\n) is left at the end of the string, and is only omitted on the last line of the file if the file doesn’t end in a newline.

  • Related