- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我正在尝试编写一个 Python 2/3 兼容例程来获取 CSV 文件,将其从 latin_1
解码为 Unicode 并将其提供给 csv.DictReader
以稳健、可扩展的方式。
python-future
,包括从 builtins
导入 open
,以及导入 unicode_literals
一致的行为tempfile.SpooledTemporaryFile
io.TextIOWrapper
处理 latin_1
编码的解码,然后再提供给 DictReader
这在 Python 3 下一切正常。
问题是 TextIOWrapper
期望包装符合 BufferedIOBase
的流。不幸的是,在 Python 2 下,虽然我已经导入了 Python 3 风格的 open
,但是 vanilla Python 2 tempfile.SpooledTemporaryFile
当然仍然返回 Python 2 cStringIO.StringO
,而不是 TextIOWrapper
所需的 Python 3 io.BytesIO
。
我可以想到这些可能的方法:
cStringIO.StringO
包装为 Python 3 风格的 io.BytesIO
。我不确定如何处理这个问题 - 我需要编写这样的包装器还是已经存在?cStringIO.StringO
流以进行解码。我还没有找到。SpooledTemporaryFile
,完全在内存中解码。 CSV 文件需要多大才能完全在内存中运行才会成为问题?SpooledTemporaryFile
,并实现我自己的溢出到磁盘。这将允许我从 python-future 调用 open
,但我宁愿不这样做,因为它会非常乏味而且可能不太安全。最好的前进方向是什么?我错过了什么吗?
导入:
from __future__ import (absolute_import, division,
print_function, unicode_literals)
from builtins import (ascii, bytes, chr, dict, filter, hex, input, # noqa
int, map, next, oct, open, pow, range, round, # noqa
str, super, zip) # noqa
import csv
import tempfile
from io import TextIOWrapper
import requests
初始化:
...
self._session = requests.Session()
...
常规:
def _fetch_csv(self, path):
raw_file = tempfile.SpooledTemporaryFile(
max_size=self._config.get('spool_size')
)
csv_r = self._session.get(self.url + path)
for chunk in csv_r.iter_content():
raw_file.write(chunk)
raw_file.seek(0)
text_file = TextIOWrapper(raw_file._file, encoding='latin_1')
return csv.DictReader(text_file)
错误:
...in _fetch_csv
text_file = TextIOWrapper(raw_file._file, encoding='utf-8')
AttributeError: 'cStringIO.StringO' object has no attribute 'readable'
最佳答案
不确定这是否有用。这种情况与您的情况只有模糊的相似之处。
我想使用 NamedTemporaryFile创建一个 CSV 以 UTF-8 编码并具有操作系统 native 行结尾,可能不完全- standard , 但使用 Python 3 风格的 io.open 很容易适应。
难点在于Python 2中的NamedTemporaryFile打开一个字节流,导致problems with line endings .我确定的解决方案是创建临时文件,然后关闭它并使用 io.open 重新打开,我认为它比 Python 2 和 3 的单独案例要好一些。最后一 block 是优秀的backports.csv在 Python 2 中提供 Python 3 样式 CSV 处理的库。
from __future__ import absolute_import, division, print_function, unicode_literals
from builtins import str
import csv, tempfile, io, os
from backports import csv
data = [["1", "1", "John Coltrane", 1926],
["2", "1", "Miles Davis", 1926],
["3", "1", "Bill Evans", 1929],
["4", "1", "Paul Chambers", 1935],
["5", "1", "Scott LaFaro", 1936],
["6", "1", "Sonny Rollins", 1930],
["7", "1", "Kenny Burrel", 1931]]
## create CSV file
with tempfile.NamedTemporaryFile(delete=False) as temp:
filename = temp.name
with io.open(filename, mode='w', encoding="utf-8", newline='') as temp:
writer = csv.writer(temp, quoting=csv.QUOTE_NONNUMERIC, lineterminator=str(os.linesep))
headers = ['X', 'Y', 'Name', 'Born']
writer.writerow(headers)
for row in data:
print(row)
writer.writerow(row)
关于python - 使用 python-future 解码 Python 2 `tempfile`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34823113/
我需要创建一个临时目录来存放另一个命名目录和子文件。最后,指定的目录和子文件将附加到压缩包中,临时目录可以删除。最初打算使用 mkdtemp()但它看起来像 TemporaryDirectory()方
在 Heroku 托管的 Rails 3 应用程序中,一个多部分文件被发布到我的应用程序,我正在尝试使用一些示例代码: File.open(params['filename'][:tempfile].
有谁知道在 JRuby 中是如何处理 tempfile.rb 的。它在 Ruby 中,但不在 JRuby 中。 有人有任何想法吗? 干杯 埃夫 最佳答案 您仍然可以“要求'tempfile'”并且它会
我目前正在 Ruby 上运行这段代码。 file = Tempfile.new(['tempemail', '.html']) file 'xx' 如果没有 file.close,您将得到一个空字符
谁能告诉我在 python 中使用 tempfile 的好处,在什么情况下我应该使用它? 我正在编写一个程序来处理一个文件,它会先调用另一个脚本来处理该文件,生成一个临时文件并执行下一步,我将自己编写
在上传到新目的地之前,我使用 Tempfile 存储生成的 PDF。 pdf_file = WickedPdf.new.pdf_from_string(msgbody) tempfil
我正在尝试创建一个临时文件并向其中写入一些文本。但是我在控制台中得到了这种奇怪的行为 t = Tempfile.new("test_temp") # => # t # t.write("test d
我们的处理服务器主要与 TempFiles 一起工作,因为它使我们这边的事情变得更容易:无需注意删除它们,因为它们会被垃圾收集或处理名称冲突等。 最近,我们遇到了 TempFiles 在此过程中过早进
我正在更改文件的内容,因此我逐行读取文件,替换我想要的内容并逐行写入临时文件。处理整个文件后,我删除原始文件,并将临时文件重命名为原始文件名。像这样 File orginialFile = new F
我正在使用 django 和 Google App Engine。我无法确定错误来自哪里,因为如果我在本地使用它,我的网站就会正常运行。在我将其部署到 GAE 上之后,它工作正常,但是当使用 goog
我正在使用 tempfile.mkstemp 生成一个随机可用的文件名并使用 os.fdopen 写入一些内容。然后我通过 celery 将文件名传递给任务。 此任务打开文件,处理内容,最后删除文件。
我正在使用 tempfile.NamedTemporaryFile()存储一些文本直到程序结束。在 Unix 上工作没有任何问题,但在 Windows 上返回的文件无法读取或写入:python 给出
我一直在使用带有前缀的 tempfile.mkdtemp 来创建我的临时文件。这导致我的 tmp 文件夹中有很多不同的目录,其中包含“tmp/myprefix{uniq-string}/”。 我想改变
我有一个 GUI (lxn/walk) 应用程序修补程序,它通过 ftp 下载文件,将其流式传输到临时文件并提取内容以更新本地文件。删除文件命令被推迟。 除非用户在下载文件时退出程序,否则文件不会被删
在 python 中,您可以创建一个临时文件,如下所示: tempfile.TemporaryFile() 然后你就可以写信给它了。 GNU/Linux 系统中写入的文件在哪里?我似乎无法在/tmp
我正在编写一个 Python 脚本,该脚本需要创建大约 50 个不同的临时文件,这些文件在脚本执行过程中经常被附加并在最后合并。我确信 tempfile 模块可以满足我的需要,但我无法通过阅读文档来弄
无论如何我可以写入临时文件并将其包含在命令中,然后关闭/删除它。我想执行命令,例如:some_command/tmp/some-temp-file. 非常感谢。 import tempfile tem
我在 Python 中使用 tempfile 和 sqlite3 模块。 以下代码有效: import sqlite3, tempfile conn1 = sqlite3.connect(tempfi
根据 tempfile.mkstemp docs , mkstemp() returns a tuple containing an OS-level handle to an open file (
我想在几天内学习Java。我尝试将内容写入临时文件并将该文件保存在 Windows 中的临时文件夹中(这是我的任务)。我找到了一些解决方案,但对我不起作用:( http://www.mkyong.co
我是一名优秀的程序员,十分优秀!