我想阅读包含以下数据的csv文件:
Input.csv -
10,[40000,1][50000,5][60000,14]
20,[40000,5][50000,2][60000,1][70000,1][80000,1][90000,1]
30,[60000,4]
40,[40000,5][50000,14]
我想解析这个csv文件并逐行解析。但是这些列表包含逗号(',')所以我得不到正确的结果。
程序编码 -
if __name__ == "__main__":
with open(inputfile, "r") as f:
reader = csv.reader(f,skipinitialspace=True)
next(reader,None)
for read in reader:
no = read[0]
splitted_record = read[1]
print splitted_record
输出
[40000
[40000
[60000
[40000
我可以理解read.csv方法读取每列的逗号。但我如何将整个列表作为一列阅读?
预期输出
[40000,1][50000,5][60000,14]
[40000,5][50000,2][60000,1][70000,1][80000,1][90000,1]
[60000,4]
[40000,5][50000,14]
将内容写入其他文件 -
name_list = ['no','splitted_record']
file_name = 'temp/'+ no +'.csv'
if not os.path.exists(file_name):
f = open(file_name, 'a')
writer = csv.DictWriter(f,delimiter=',',fieldnames=name_list)
writer.writeheader()
else:
f = open(file_name, 'a')
writer = csv.DictWriter(f,delimiter=',',fieldnames=name_list)
writer.writerow({'no':no,'splitted_record':splitted_record})
如何在没有引号(“”)的情况下编写此splitted_record?
感谢所有回复!
答案 0 :(得分:1)
您可以将这些项目加在一起,因为您知道它以逗号分隔
return back();
输出
if __name__ == "__main__":
with open(inputfile, "r") as f:
reader = csv.reader(f,skipinitialspace=True)
next(reader,None)
for read in reader:
no = read[0]
splitted_record = ','.join(read[1:])
print splitted_record
--- ---更新 数据是上面的输出
[40000,1][50000,5][60000,14]
[40000,5][50000,2][60000,1][70000,1][80000,1][90000,1]
[60000,4]
[40000,5][50000,14]
答案 1 :(得分:0)
您可以使用自己的方言并根据需要进行注册。 https://docs.python.org/2/library/csv.html