Getting error when starting _exit_ when using the "c" keyword

I sent a .csv

file to send a request,

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

      

I always get an error on the second line. Also my file type Unicode

, so it again gives an error on the third line forreadline()

+3


source to share


2 answers


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

      

How to read a file using stament:

code:

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

      

Check if the file is complete or not before performing any process.

Use the os module



Demo

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

      


Uploading files to server via post request while testing API with 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 data

to the server location in the view.

+1


source


Considering what the {u'file': u'C:\\sample_datasheet.csv'}

function returns data.get()

, you should get the filename and open it:



data = data.get('file', None)
fname = data["file"]
with open(fname, "r") as datasheet:
        header = datasheet.readline()

      

+1


source







All Articles