前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python 操作 txt 文件中数据教程[4]-python 去掉 txt 文件行尾换行

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

作者头像
演化计算与人工智能
发布2020-08-14 00:12:25
2.6K0
发布2020-08-14 00:12:25
举报

参考文章

python 操作 txt 文件中数据教程[1]-使用 python 读写 txt 文件[1]

python 操作 txt 文件中数据教程[2]-python 提取 txt 文件中的行列元素[2]

python 操作 txt 文件中数据教程[3]-python 读取文件夹中所有 txt 文件并将数据转为 csv 文件[3]

误区

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

实例

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

正确做法

  • 将文件中的读取后,使用写语句将修改后的内容重新写入新的文件中
代码语言:javascript
复制
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~!!

参考资料

[1]python操作txt文件中数据教程[1]-使用python读写txt文件: https://blog.csdn.net/u013555719/article/details/84553722

[2]python操作txt文件中数据教程[2]-python提取txt文件中的行列元素: https://blog.csdn.net/u013555719/article/details/84554355

[3]python操作txt文件中数据教程[3]-python读取文件夹中所有txt文件并将数据转为csv文件: https://blog.csdn.net/u013555719/article/details/84554568

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2020-06-23,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 DrawSky 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 误区
  • 实例
    • 正确做法
      • 参考资料
      相关产品与服务
      文件存储
      文件存储(Cloud File Storage,CFS)为您提供安全可靠、可扩展的共享文件存储服务。文件存储可与腾讯云服务器、容器服务、批量计算等服务搭配使用,为多个计算节点提供容量和性能可弹性扩展的高性能共享存储。腾讯云文件存储的管理界面简单、易使用,可实现对现有应用的无缝集成;按实际用量付费,为您节约成本,简化 IT 运维工作。
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档