如何在Python中找到文本文件的线路端

发布于 2025-02-13 19:21:17 字数 935 浏览 1 评论 0原文

我有一个python3脚本,可以在Windows下运行,但可以(取决于用户的选择)产生Windows风格\ r \ n line endings,或Linux-style style \ n

if linux_style_endings:
    newline = '\n'
else:
    newline = None
with open(myfile, "w", newline=newline) as g:
    g.write("sometext\n")

手动检查确认这有效。

现在,我想编写一个单元测试以确认这一点。

我如何获得文本文件的线结尾?

(这不是忽略终点的结尾,而是实际上找出了哪些已使用。)

我到目前为止尝试过的是:< /strong>

以下将读取内容并将行结尾转换为相同的值。它在任何一行结束时都会产生相同的结果,因此我无法使用它来检查:

with open(myfile.txt, "r") as f:
    f.read()

以下[i] do [/i]显示行结尾:

with open(output_fastq, "rb") as f:
    text = f.read()
    print(text.splitlines(keepends=True))

这将返回EG [B'Sometext \ n']对于Linux行结束,[B'Sometext \ r \ n']对于Windows行结束。

没有比制作参考文件和比较二进制f.read()的结果更优雅的方法。

I have a Python3 script that runs under Windows but can (depending on the user's choice) produce either Windows-Style \r\n line endings, or Linux-style \n.

if linux_style_endings:
    newline = '\n'
else:
    newline = None
with open(myfile, "w", newline=newline) as g:
    g.write("sometext\n")

Manual checks confirm that this works.

Now I want to write a unit test to confirm this.

How can I get the line endings of a text file?

(So this is not about ignoring the line endings, but actually finding out which are used.)

What I have tried so far:

The following will read the content and convert the line endings to the same values. It produces identical results with either line ending, so I cannot use it to check:

with open(myfile.txt, "r") as f:
    f.read()

The following [i]does[/i] show the line endings:

with open(output_fastq, "rb") as f:
    text = f.read()
    print(text.splitlines(keepends=True))

This will return e.g. [b'sometext\n'] for the linux line ends, and [b'sometext\r\n'] for the windows line ends.

Isn't there a more elegant way than producing a reference file and comparing the results of a binary f.read().splitlines(keepends=True)?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文