我试图用Python列表中的值创建一个.csv文件。当我打印列表中的值时,它们都是unicode(?),即它们看起来像这样
[u'value 1', u'value 2', ...]
如果我遍历列表中的值,即mylist中的v:打印v,它们看起来是纯文本。
然后在每一个之间加上print '。join(mylist)
我可以输出到一个文件,即。
myfile = open(...)
print >>myfile, ','.join(mylist)
但是我想输出到CSV,并在列表中的值周围有分隔符。
"value 1", "value 2", ...
我找不到一个简单的方法来包括在格式分隔符,例如,我已经尝试通过连接语句。我该怎么做呢?
你可以用绳子。方法。
为了清晰起见,分成几行——这是一个交互式会话
>>> a = ['a','b','c']
>>> first = '", "'.join(a)
>>> second = '"%s"' % first
>>> print second
"a", "b", "c"
或者是一条直线
>>> print ('"%s"') % '", "'.join(a)
"a", "b", "c"
然而,你可能有一个问题是你的字符串有嵌入引号。如果是这种情况,你需要决定如何逃离它们。
CSV模块可以为您处理所有这些,允许您在各种引用选项(所有字段,仅包含引号和分隔符的字段,仅包含非数字字段,等等)之间进行选择,以及如何转义控制字符(双引号,或转义字符串)。如果你的值是简单的,字符串。join可能没问题,但如果你必须管理大量的边缘情况,使用可用的模块。
使用python的csv模块来读写逗号或制表符分隔的文件。csv模块是首选,因为它可以很好地控制引用。
例如,下面是你的工作示例:
import csv
data = ["value %d" % i for i in range(1,4)]
out = csv.writer(open("myfile.csv","w"), delimiter=',',quoting=csv.QUOTE_ALL)
out.writerow(data)
生产:
"value 1","value 2","value 3"
你当然应该使用CSV模块,但你可能需要编写unicode。对于那些需要编写unicode的人,这是来自示例页面的类,您可以将其用作util模块:
import csv, codecs, cStringIO
class UTF8Recoder:
"""
Iterator that reads an encoded stream and reencodes the input to UTF-8
"""
def __init__(self, f, encoding):
self.reader = codecs.getreader(encoding)(f)
def __iter__(self):
return self
def next(self):
return self.reader.next().encode("utf-8")
class UnicodeReader:
"""
A CSV reader which will iterate over lines in the CSV file "f",
which is encoded in the given encoding.
"""
def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
f = UTF8Recoder(f, encoding)
self.reader = csv.reader(f, dialect=dialect, **kwds)
def next(self):
row = self.reader.next()
return [unicode(s, "utf-8") for s in row]
def __iter__(self):
return self
class UnicodeWriter:
"""
A CSV writer which will write rows to CSV file "f",
which is encoded in the given encoding.
"""
def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
# Redirect output to a queue
self.queue = cStringIO.StringIO()
self.writer = csv.writer(self.queue, dialect=dialect, **kwds)
self.stream = f
self.encoder = codecs.getincrementalencoder(encoding)()
def writerow(self, row):
self.writer.writerow([s.encode("utf-8") for s in row])
# Fetch UTF-8 output from the queue ...
data = self.queue.getvalue()
data = data.decode("utf-8")
# ... and reencode it into the target encoding
data = self.encoder.encode(data)
# write to the target stream
self.stream.write(data)
# empty queue
self.queue.truncate(0)
def writerows(self, rows):
for row in rows:
self.writerow(row)
我发现最好的选择是使用numpy模块中的savetxt:
import numpy as np
np.savetxt("file_name.csv", data1, delimiter=",", fmt='%s', header=header)
以防你有多个需要堆叠的列表
np.savetxt("file_name.csv", np.column_stack((data1, data2)), delimiter=",", fmt='%s', header=header)
下面是另一个不需要csv模块的解决方案。
print ', '.join(['"'+i+'"' for i in myList])
例子:
>>> myList = [u'value 1', u'value 2', u'value 3']
>>> print ', '.join(['"'+i+'"' for i in myList])
"value 1", "value 2", "value 3"
但是,如果初始列表包含一些“,则不会转义。如果需要,可以调用一个函数像这样转义它:
print ', '.join(['"'+myFunction(i)+'"' for i in myList])
创建并写入csv文件
下面的示例演示创建和写入csv文件。
要使一个动态文件写入器,我们需要导入一个包import csv,然后需要创建一个文件引用的文件实例
Ex:-使用open("D:\sample.csv","w",newline="")作为文件写入器
here if the file does not exist with the mentioned file directory then python will create a same file in the specified directory, and "w" represents write, if you want to read a file then replace "w" with "r" or to append to existing file then "a". newline="" specifies that it removes an extra empty row for every time you create row so to eliminate empty row we use newline="", create some field names(column names) using list like fields=["Names","Age","Class"], then apply to writer instance like
writer=csv.DictWriter(file_writer,fieldnames=fields)
here using Dictionary writer and assigning column names, to write column names to csv we use writer.writeheader() and to write values we use writer.writerow({"Names":"John","Age":20,"Class":"12A"}) ,while writing file values must be passed using dictionary method , here the key is column name and value is your respective key value
import csv
with open("D:\\sample.csv","w",newline="") as file_writer:
fields=["Names","Age","Class"]
writer=csv.DictWriter(file_writer,fieldnames=fields)
writer.writeheader()
writer.writerow({"Names":"John","Age":21,"Class":"12A"})
下面是Python 3的复制粘贴示例。使用选项定义自己的分隔符和引号字符。
import csv
mylist = ['value 1', 'value 2', 'value 3']
with open('employee_file.csv', mode='w') as employee_file:
employee_writer = csv.writer(employee_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_ALL)
employee_writer.writerow(mylist)
这会生成employee_file.csv,如下所示:
"value 1","value 2","value 3"
NOTE:
If quoting is set to csv.QUOTE_MINIMAL, then .writerow() will quote
fields only if they contain the delimiter or the quotechar. This is
the default case.
If quoting is set to csv.QUOTE_ALL, then .writerow() will quote all
fields.
If quoting is set to csv.QUOTE_NONNUMERIC, then .writerow() will quote
all fields containing text data and convert all numeric fields to the
float data type.
If quoting is set to csv.QUOTE_NONE, then .writerow() will escape
delimiters instead of quoting them. In this case, you also must
provide a value for the escapechar optional parameter.