[Solved]-How to get (txt) file content from FileField?

8👍

Since Django 2.0 File.open does return you a file, so suggested way to work is as with context manager:

saved_file = MyModel.objects.all().get(id=0).saved_file
with saved_file.open() as f:
    data = f.readlines()

Applies to old versions of Django < 2

FieldFile.open opens the file, but doesn’t return anything. So in your example file is None.

You should call readlines on FieldFile. In your example it would be:

f = MyModel.objects.all().get(id=0).saved_file
try:
    f.open(mode='rb') 
    lines = f.readlines()
finally:
    f.close()

UPD: I added try/finally block, as the good practice is to always close the resource, even if exception happened.

👤Igor

8👍

The documentation states that files are opened in ‘rb’ mode by default, but you would want to open in ‘r’ to treat the file as a text file:

my_object = MyModel.objects.get(pk=1)
try:
    my_object.saved_file.open('r')
    lines = my_object.saved_file.readlines()
finally:
    my_object.saved_file.close()

Even better, you can use a context manager in Django v2.0+

my_object = MyModel.objects.get(pk=1)
with my_object.saved_file.open('r') as f:
    lines = f.readlines()

Leave a comment