我试图将Python 3程序反向移植到2.7,我遇到了一个奇怪的问题:
>>> import io
>>> import csv
>>> output = io.StringIO()
>>> output.write("Hello!") # Fail: io.StringIO expects Unicode
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unicode argument expected, got 'str'
>>> output.write(u"Hello!") # This works as expected.
6L
>>> writer = csv.writer(output) # Now let's try this with the csv module:
>>> csvdata = [u"Hello", u"Goodbye"] # Look ma, all Unicode! (?)
>>> writer.writerow(csvdata) # Sadly, no.
Traceback (most recent call last):
File "<stdin>", …Run Code Online (Sandbox Code Playgroud) 我有一个example.csv包含内容的文件
1,"A towel,",1.0
42," it says, ",2.0
1337,is about the most ,-1
0,massively useful thing ,123
-2,an interstellar hitchhiker can have.,3
Run Code Online (Sandbox Code Playgroud)
我如何example.csv用Python 阅读?
同样,如果我有
data = [(1, "A towel,", 1.0),
(42, " it says, ", 2.0),
(1337, "is about the most ", -1),
(0, "massively useful thing ", 123),
(-2, "an interstellar hitchhiker can have.", 3)]
Run Code Online (Sandbox Code Playgroud)
如何data使用Python 写入CSV文件?
我想用逗号将文本写入CSV文件中的单元格.
输入
'1,2,3,Hello'
CSV输出应该是
'1,2,3','Hello'
我想记录每个请求的一些信息以格式化的形式发送到繁忙的http服务器,使用日志模块会创建一些我不想要的东西:
[I 131104 15:31:29 Sys:34]
Run Code Online (Sandbox Code Playgroud)
我想到csv格式,但我不知道如何自定义它,而python有csv模块,但阅读手册
import csv
with open('some.csv', 'w', newline='') as f:
writer = csv.writer(f)
writer.writerows(someiterable)
Run Code Online (Sandbox Code Playgroud)
因为它每次都会打开和关闭一个文件,我担心这样会降低整个服务器的性能,我该怎么办?
在 Python 中,我有一个像这样的字典列表:
[
{
"col2": "2",
"id": "1",
"col3": "3",
"col1": "1"
},
{
"col2": "4",
"id": "2",
"col3": "6",
"col1": "2"
},
{
"col1": "1",
"col2": "4",
"id": "3",
"col3": "7"
}
]
Run Code Online (Sandbox Code Playgroud)
我需要将其转换为 csv 格式的字符串,包括标题行。(对于初学者来说,我们不关心列和行分隔符......)所以,理想的结果是:
id,col1,col2,col3
1,1,2,3
2,2,4,6
3,1,4,7
Run Code Online (Sandbox Code Playgroud)
(“理想情况下”,因为列顺序并不重要;不过,先有“id”列会很好......)
我搜索过 SOF,有很多类似的问题,但答案总是涉及使用 csv.DictWriter 创建 csv文件。我不想创建文件,我只想那个字符串!
当然,我可以循环遍历列表,并在该循环内循环遍历字典键,并以这种方式使用字符串操作创建 csv 字符串。但肯定有一些更优雅、更有效的方法来做到这一点吗?
另外,我知道 Pandas 库,但我试图在非常有限的环境中执行此操作,在该环境中我更愿意仅使用内置模块。
请考虑以下内容(Windows下的Python 3.2):
>>> import io
>>> import csv
>>> output = io.StringIO() # default parameter newline=None
>>> csvdata = [1, 'a', 'Whoa!\nNewlines!']
>>> writer = csv.writer(output, quoting=csv.QUOTE_NONNUMERIC)
>>> writer.writerow(csvdata)
25
>>> output.getvalue()
'1,"a","Whoa!\nNewlines!"\r\n'
Run Code Online (Sandbox Code Playgroud)
为什么有一个\n- 不应该已经转换为\r\n自启用通用换行模式?
启用此功能,在输入,线路的结局
\n,\r或\r\n将被转换为\n被返回给调用者之前.相反,在输出时,\n转换为系统默认行分隔符,os.linesep.
csv ×6
python ×6
python-3.x ×2
dictionary ×1
list ×1
logging ×1
newline ×1
python-2.7 ×1
string ×1
unicode ×1