[英]How to read list which contains comma from CSV file as a column?
I want to read CSV file which contains following data :我想读取包含以下数据的 CSV 文件:
Input.csv-输入.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]
I want to parse this CSV file and parse it row by row.我想解析这个 CSV 文件并逐行解析它。 But these lists contains commas
','
so I'm not getting correct result.但是这些列表包含逗号
','
所以我没有得到正确的结果。
Program-Code-程序代码-
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
Output-输出-
[40000
[40000
[60000
[40000
I can understand read.csv
method reads till commas for each column.我可以理解
read.csv
方法读取每列的逗号。 But how I can read whole lists as a one column?但是我如何将整个列表作为一列阅读?
Expected Output-预期输出-
[40000,1][50000,5][60000,14]
[40000,5][50000,2][60000,1][70000,1][80000,1][90000,1]
[60000,4]
[40000,5][50000,14]
Writing stuff to other file-将内容写入其他文件-
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})
How I can write this splitted_record
without quote ""
?我怎样才能写这个
splitted_record
没有引号""
?
you can join those items together, since you know it split by comma您可以将这些项目连接在一起,因为您知道它用逗号分隔
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
output输出
[40000,1][50000,5][60000,14]
[40000,5][50000,2][60000,1][70000,1][80000,1][90000,1]
[60000,4]
[40000,5][50000,14]
---update--- data is the above output ---更新---数据是上面的输出
with open(filepath,'wb') as f:
w = csv.writer(f)
for line in data:
w.writerow([line])
You can use your own dialect and register it to read as you need.您可以使用自己的方言并将其注册为您需要的阅读。 https://docs.python.org/2/library/csv.html
https://docs.python.org/2/library/csv.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.