我目前有;
files = ['a.txt', 'b.txt', 'c.txt']
ftypes = [['a', 'b'], ['c'], ['a', 'b', 'c']]
with open('files.csv', 'wb') as file:
writer = csv.writer(file, quoting=csv.QUOTE_MINIMAL)
for f, g in zip(files, ftypes):
writer.writerow((f, g))
在我使用中阅读;
with open('files.csv', 'r') as rfile:
csvread = csv.reader(rfile)
files = []
ftypes = []
for row in csvread:
files.append(row[0])
ftypes.append(row[1])
在实际的csv中,第二列填充正确,子列表填充第二列,但是在读取ftypes时,它返回[" [' a',' ; b']"," [' c']"," [' a',' b&# 39;,' c']"]这是不正确的。它将它视为一个字符串列表,所以我不能像这样循环它们;
for i in ftypes:
for j in i:
print(j)
如何修复我的书写/阅读以便嵌套列表正确解析?
编辑:
CSV文件内容
a.txt,"['a', 'b']"
b.txt,"['c']"
c.txt,"['a', 'b', 'c']"
似乎Excel 2013正在解析双引号并忽略它们,但是python正在正确地解析实际的csv内容。我需要将哪些参数传递给csv.writer来纠正这个问题?
答案 0 :(得分:2)
我认为你应该使用Convert string representation of list to list in Python。
发生的事情非常明显 - Python读取CSV行,行中的每个元素都是一个字符串。它不知道它应该是什么类型。
所以你会有像
这样的东西import ast
with open('files.csv', 'r') as rfile:
csvread = csv.reader(rfile)
files = []
g_list = []
for row in csvread:
files.append(row[0])
ftypes.append(ast.literal_eval(row[1]))
为了避免这种破解并修复完全写入,您可以执行以下操作:
files = ['a.txt', 'b.txt', 'c.txt']
ftypes = [['a', 'b'], ['c'], ['a', 'b', 'c']]
with open('files.csv', 'wb') as file:
writer = csv.writer(file, quoting=csv.QUOTE_MINIMAL)
for f, g in zip(files, ftypes):
g.insert(0, f)
writer.writerow(g)
ftypes_from_file = []
files_from_file = []
with open('files.csv', 'r') as rfile:
csvread = csv.reader(rfile)
files = []
g_list = []
for row in csvread:
files_from_file.append(row[0])
ftype = []
for item in row[1:]:
ftype.append(item)
ftypes_from_file.append(ftype)
print(ftypes_from_file)
它主要用于处理行中项目的动态计数。
我希望CSV中新行的格式对您有用。