Python removes line endings of txt files

Misunderstanding

  • Use python to read the txt file using the statement open(filename,'r')
  • Use python to write the txt file using the statement open(fileneme,'w')
  • So if you want to read the original file through python, directly rewrite it to the original file, that is, read the "\n" or "\r\n" in the original file, and then delete the characters directly. This is not realistic of. It should first read the original file content through open(filename,'r'), and then use open(fileneme,'w') to write the string with the carriage return at the end of the line deleted to the new file. That is to do read and write separation.

Instance

For the original file,
Insert picture description here
using the following statement only deletes the newline character at the end of the line, instead of actually writing the modified result into the original file.

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:778463939
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
filename = "./text.txt"
with open(filename, 'r') as f:
    print("open OK")
    for line in f.readlines():
        for a in line:
            # print(a)
            if a == '\n':
                print("This is \\n")
                a = " "
    for line in f.readlines():
        for a in line:
            if a == '\n':
                print("This is \\r\\n")
    for line in f.readlines():
        line = line.replace("\n", " ")
        line = line.strip("\n")

"""open OK
This is \n
This is \n
This is \n
This is \n
This is \n
This is \n
This is \n
This is \n
This is \n
This is \n
This is \n
This is \n
This is \n
This is \n
This is \n
This is \n
"""

But the original file has not been modified

Correct way

After reading the file, use the write statement to rewrite the modified content into the new file

with open('./text_1.txt', 'w') as f:
    with open('./text.txt', 'r') as fp:
        for line in fp:
            line = str(line).replace("\n", " ")
            f.write(line)

Insert picture description here

Guess you like

Origin blog.csdn.net/qdPython/article/details/112966125