如何在Python中找到文本文件的线路端
我有一个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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论