使用 "with" 关键字时获取属性错误 __exit__

Getting Attrbute error _exit_ when use "with" keyword

我已将 .csv 文件传递​​给 post 请求,

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

总是在第二行出现错误。另外我的文件类型是 Unicode 这就是为什么它再次在第三行给出错误 readline()

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

如何使用 with 语句读取文件:

代码:

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

在进行任何处理之前检查文件是否存在。

使用os模块

演示:

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

使用 tastypie

在 API 测试中通过 post 请求上传文件到服务器
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))

并将 contentdata 保存到视图中的服务器位置。

考虑到{u'file': u'C:\sample_datasheet.csv'}是由data.get()函数返回的,需要获取文件名并打开:

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