MagicforestA 2022-06-24 12:35 采纳率: 100%
浏览 17
已结题

python读取文件换行的问题

这段代码如何做到自动换行读取


from os import strerror

try:
    cnt = 0
    s = open("textfile.txt", "rt", encoding = "utf-8")
    ch = s.read(1)
    while ch != '':
        print(ch, end='')
        cnt += 1
        ch = s.read(1)
    s.close()
    print("\n\nCharacters in file:", cnt)
except IOError as e:
    print("I/O error occurred: ", strerror(e.errno))


output:
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

Characters in file: 726
  • 写回答

2条回答 默认 最新

  • CSDN专家-sinJack 2022-06-24 13:06
    关注

    文件中的换行符\n

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 7月2日
  • 已采纳回答 6月24日
  • 创建了问题 6月24日

悬赏问题

  • ¥15 vscode调试编译找不到gcc,只有cl,但是检查cmd是对的,控制面板的路径也更改了
  • ¥15 FlycoRoundView引入失败
  • ¥20 access中怎么分割分别获取一下图中的值
  • ¥15 keras_tcn已经安装成功,还是显示ModuleNotFoundError: No module named 'keras_tcn'
  • ¥15 类图中关联与聚合的区别
  • ¥15 ENVI高分五号去除云层的方法
  • ¥15 16进制数据如何得到奇偶校验位
  • ¥15 求合并两个字节流VB6代码
  • ¥15 Pyqt 如何正确的关掉Qthread,并且释放其中的锁?
  • ¥30 网站服务器通过node.js部署了一个项目!前端访问失败