如何在python中使用csv的分隔符 [英] How to use delimiter for csv in python

查看:1333
本文介绍了如何在python中使用csv的分隔符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法找出如何在Python中使用csv.writer的分隔符。
我有一个csv文件,其中用逗号分隔的字符串在单个单元格中,我需要在每个单独的单元格中有每个单词。例如:

  100,2559 ,, Main,St,LEOMA,LEOMA,498,498,AK,AK 
140 ,425 ,, Main,St,LEOMA,LEOMA,498,498,AK,AK
100,599 ,, Main,St,LEOMA,LEOMA,498,498,AK,AK

应为

  100 2559 Main St LEOMA LEOMA 498 498 AK AK 
140 425 Main St LEOMA LEOMA 498 498 AK AK
100 599 Main St LEOMA LEOMA 498 498 AK AK



我试过:



pre> import csv
workingdir =C:\Mer\Ven\sample
csvfile = workingdir +\test3.csv
f = open(csvfile,'wb')

csv.writer(f,delimiter ='',quotechar =',',quoting = csv.QUOTE_MINIMAL)


解决方案

您的代码会将您的文件留空:

  import csv 
workingdir =C:\Mer\Ven\sample
csvfile = workingdir +\test3.csv
f = open(csvfile,'wb')#打开写入文件(擦除内容)
csv.writer(f,delimiter ='',quotechar =',',quoting = csv.QUOTE_MINIMAL)

如果要读取文件,则需要使用csv.reader并打开文件进行读取。 p>

  import csv 
workingdir =C:\Mer\Ven\sample
csvfile = workingdir + \test3.csv
f = open(csvfile,'rb')#打开读取文件
reader = csv.reader(f)
读取线:
打印行

如果要将其写回具有不同分隔符的新文件,一个新文件并指定这些分隔符并写出每一行(而不是打印元组)。


I'm having trouble with figuring out how to use the delimiter for csv.writer in Python. I have a csv file in which the strings separated by commas are in single cell and I need to have each word in each individual cell. For ex:

   100 , 2559   ,,Main, St,LEOMA,LEOMA,498,498, AK,AK
   140 , 425    ,,Main, St,LEOMA,LEOMA,498,498, AK,AK
   100 , 599    ,,Main, St,LEOMA,LEOMA,498,498, AK,AK

should be

   100  2559        Main    St  LEOMA   LEOMA   498 498 AK  AK
   140  425     Main    St  LEOMA   LEOMA   498 498 AK  AK
   100  599     Main    St  LEOMA   LEOMA   498 498 AK  AK

(each word in individual cell).

I tried:

import csv
workingdir = "C:\Mer\Ven\sample"
csvfile = workingdir+"\test3.csv"
f=open(csvfile,'wb')

csv.writer(f, delimiter =' ',quotechar =',',quoting=csv.QUOTE_MINIMAL)

解决方案

Your code is blanking out your file:

import csv
workingdir = "C:\Mer\Ven\sample"
csvfile = workingdir+"\test3.csv"
f=open(csvfile,'wb') # opens file for writing (erases contents)
csv.writer(f, delimiter =' ',quotechar =',',quoting=csv.QUOTE_MINIMAL)

if you want to read the file in, you will need to use csv.reader and open the file for reading.

import csv
workingdir = "C:\Mer\Ven\sample"
csvfile = workingdir+"\test3.csv"
f=open(csvfile,'rb') # opens file for reading
reader = csv.reader(f)
for line in reader:
    print line

If you want to write that back out to a new file with different delimiters, you can create a new file and specify those delimiters and write out each line (instead of printing the tuple).

这篇关于如何在python中使用csv的分隔符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆