回答此问题可获得 20 贡献值,回答如果被采纳可获得 50 分。
<p>所以我正在处理一个csv文件,它缺少值。
我想要我的剧本是:</p>
<pre><code>#!/usr/bin/python
import csv
import sys
#1. Place each record of a file in a list.
#2. Iterate thru each element of the list and get its length.
#3. If the length is less than one replace with value x.
reader = csv.reader(open(sys.argv[1], "rb"))
for row in reader:
for x in row[:]:
if len(x)< 1:
x = 0
print x
print row
</code></pre>
<p>下面是一个数据示例,我正在尝试它,理想情况下它应该可以在任何列长度上工作</p>
<pre><code>Before:
actnum,col2,col4
xxxxx , ,
xxxxx , 845 ,
xxxxx , ,545
After
actnum,col2,col4
xxxxx , 0 , 0
xxxxx , 845, 0
xxxxx , 0 ,545
</code></pre>
<p>如有任何指导,将不胜感激</p>
<p>以下是我的最新情况(谢谢):</p>
<pre><code>reader = csv.reader(open(sys.argv[1], "rb"))
for row in reader:
for i, x in enumerate(row):
if len(x)< 1:
x = row[i] = 0
print row
</code></pre>
<p>但是它似乎只输出一条记录,我将在命令行上将输出管道化到一个新文件。</p>
<p>更新3:好的,现在我有一个相反的问题,我输出每个记录的副本。
为什么会这样?</p>
<pre><code>After
actnum,col2,col4
actnum,col2,col4
xxxxx , 0 , 0
xxxxx , 0 , 0
xxxxx , 845, 0
xxxxx , 845, 0
xxxxx , 0 ,545
xxxxx , 0 ,545
</code></pre>
<p>好的,我修好了,谢谢你们的帮助。</p>
<pre><code>#!/usr/bin/python
import csv
import sys
#1. Place each record of a file in a list.
#2. Iterate thru each element of the list and get its length.
#3. If the length is less than one replace with value x.
reader = csv.reader(open(sys.argv[1], "rb"))
for row in reader:
for i, x in enumerate(row):
if len(x)< 1:
x = row[i] = 0
print ','.join(str(x) for x in row)
</code></pre>