带有自定义分隔符的 Python readline [英] Python readline with custom delimiter

查看:87
本文介绍了带有自定义分隔符的 Python readline的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里是新手.我正在尝试从文件中读取行,但是 .txt 文件中的一行在中间某处有一个 \n 并且在尝试使用 .readline python 从中间切开,输出为两行.

  • 当我将该行复制并粘贴到此窗口时,它显示为两行.所以我在这里上传了文件:

    解决方案

    Python 3 允许您定义特定文件的换行符.很少使用,因为默认的universal newlines 模式非常宽容:

    <块引用>

    从流中读取输入时,如果换行符为 None,则启用通用换行符模式.输入中的行可以以 '\n'、'\r' 或 '\r\n' 结尾,这些在返回给调用者之前会被转换为 '\n'.

    所以在这里你应该明确指出只有 '\r\n' 是行尾:

    f= open("f.txt",mode='r',encoding='utf8', newline='\r\n')# 使用 enumerate 显示第二行是整体读取的对于 i,enumerate(fd) 中的行:打印(我,行)

    novice here. I am trying to read lines from a file, however a single line in a .txt file has a \n in the middle somewhere and while trying to read that line with .readline python cuts it in the middle and outputs as two lines.

    • when I copy and past the line to this window, it shows up as two lines. So i uploaded the file here: https://ufile.io/npt3n

    • also added screenshot of the file as it shows in txt file.

    • this is group chat history exported from Whatsup..if you are wondering.
    • Please help me to read one line completely as shown in txt file.

    .

    f= open("f.txt",mode='r',encoding='utf8')
    
    for i in range(4):
        lineText=f.readline()
        print(lineText)
    
    f.close()
    

    解决方案

    Python 3 allows you to define what is the newline for a particular file. It is seldom used, because the default universal newlines mode is very tolerant:

    When reading input from the stream, if newline is None, universal newlines mode is enabled. Lines in the input can end in '\n', '\r', or '\r\n', and these are translated into '\n' before being returned to the caller.

    So here you should made explicit that only '\r\n' is an end of line:

    f= open("f.txt",mode='r',encoding='utf8', newline='\r\n')
    
    # use enumerate to show that second line is read as a whole
    for i, line in enumerate(fd):   
        print(i, line)
    

    这篇关于带有自定义分隔符的 Python readline的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆