Search code examples
pythondjangotastypie

Getting Attrbute error _exit_ when use "with" keyword


I have passed .csv file to post request,

input_file = data.get('file', None)
with input_file as datasheet:
        header = datasheet.readline()

Always I am getting error on second line. Also my file type is Unicode thats why it again giving error on third line for readline()


Solution

  • >>> with "test1.html" as fp:
    ...    header = fp.readline()
    ... 
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    AttributeError: __exit__
    >>> 
    

    How to Read file with with stament:

    code:

    >>> with open("test1.html") as fp:
    ...    header = fp.readline()
    ... 
    

    Check file is exits or not before doing any process.

    Use os module

    Demo:

    >>> os.path.isfile("test1.html")
    True
    >>> os.path.isfile("nofile.html")
    False
    >>> 
    

    File Upload to server via post request in API testing using tastypie

    fp = open("C:\sample_datasheet.csv", 'rb')
    content = fp.read()
    fp.close()
    
    fd ={'file': "C:\sample_datasheet.csv", "content": content}
    self.assertHttpOK(self.api_client.post('api of upload', format='json',\
    org_id=2, content_type="multipart/form-data",\
    data=fd))
    

    and Save content from the data to server location in the view.