python操作txt文件中数据教程[4]-python去掉txt文件行尾换行

python操作txt文件中数据教程[4]-python去掉txt文件行尾换行

觉得有用的话,欢迎一起讨论相互学习~Follow Me

参考文章
python操作txt文件中数据教程[1]-使用python读写txt文件
python操作txt文件中数据教程[2]-python提取txt文件中的行列元素
python操作txt文件中数据教程[3]-python读取文件夹中所有txt文件并将数据转为csv文件

误区

  • 使用python对txt文件进行读取使用的语句是open(filename, 'r')
  • 使用python对txt文件进行写入使用的语句是open(fileneme, 'w')
  • 所以如果 要通过python对原始文件读取后,直接进行重新写入到原始文件 , 即读到原始文件中有"\n"或"\r\n" 的地方,然后直接删除字符这是不现实的。应该是先通过 open(filename, 'r') 读取原始文件内容,再使用open(fileneme, 'w') 将删除了行尾回车符的字符串写入到新的文件中。 即要做 读写分离

实例

  • 对于原始文件
  • 使用以下语句只是对读出的内容删除了行尾的换行符,而不是真正将修改的结果写入到原始的文件中。
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
"""
  • 但是原始文件并没有被修改

正确做法

  • 将文件中的读取后,使用写语句将修改后的内容重新写入新的文件中
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)

  • It's very nice~!!

猜你喜欢

转载自www.cnblogs.com/cloud-ken/p/10253965.html