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
).
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.
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.
In Python, the new line character “\n” is used to create a new line.
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:
.....
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With