Computer >> Computer tutorials >  >> Programming >> Python

What does the 'U' modifier do when a file is opened using Python?


In a Python with universal newline support open() the mode parameter can also be "U", meaning "open for input as a text file with universal newline interpretation". This is needed for crossplatform support as newlines on Unix os are represented by a single character \n while those on windows are represented by 2 characters \r\n. When opened in Python, All line ending conventions will be translated to a "\n" in the strings returned by the various file methods such as read() and readline(). For example you have a file on windows with the text −

Example

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())

Output

You'll get the output −

Hello\nworld