Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Python, how to assert passed-in file object was opened with newline=''?

I am writing a function that takes in a file object, e.g.

def my_fn(file_obj):
    assert <what expression here?>, "file_obj must be opened with newline=''."
    ...

The first thing I want to do in the function is ensure that the passed-in file object was opened with newline=''. How do I do this? Thanks.

PS. I believe this question is only applicable to Python 3 because newline='' only exists in Python 3 (note it's different from the default newline=None).

like image 522
walrus Avatar asked Jun 22 '15 16:06

walrus


People also ask

How do I read a text file line by line in Python?

Method 1: Read a File Line by Line using readlines() readlines() is used to read all the lines at a single go and then return them as each line a string element in a list. This function can be used for small files, as it reads the whole file content to the memory, then split it into separate lines.

How do you read the next line in Python?

Python file method next() is used when a file is used as an iterator, typically in a loop, the next() method is called repeatedly. This method returns the next input line, or raises StopIteration when EOF is hit. Combining next() method with other file methods like readline() does not work right.

How do you move to the next line in a text file in Python?

In Python, the new line character “\n” is used to create a new line.


1 Answers

Without parsing the source at runtime using ast I don't think it is going to be easy or possible at all to get the info from the file object, you could maybe make sure the newline was None or "" by reading a line then checking the newlines attribute but I am not sure that the newlines attribute is even always going to be available:

    next(f)
    if f.newlines is None:
        raise ValueError("...")
    else:
        f.seek(0)

But if you could only accept a file object from a function that takes a filename and open the file yourself so you would be in control:

def open_fle(f, mode="r"):
    with open(f, mode=mode,  newline="") as f:
         .....
like image 187
Padraic Cunningham Avatar answered Oct 10 '22 18:10

Padraic Cunningham