使用Python打开文件时,“ U”修饰符有什么作用?

在具有通用换行符支持open()的Python中,mode参数也可以是“ U”,表示“打开以通用换行符解释的文本文件形式输入”。这是跨平台支持所必需的,因为Unix os上的换行用单个字符\ n表示,而Windows上的换行用2个字符\ r \ n表示。在Python中打开时,所有行结尾约定都会在各种文件方法(例如read()和)返回的字符串中转换为“ \ n” readline()。例如,您在Windows上有一个文件,文本为-

示例

Hello\r\nworld
When you open it in Python using the 'U' modifier, and read it:
with open('hello.txt', 'rU') as f:
    print(f.read())

输出结果

您将获得输出-

Hello\nworld