我喜欢学习Python,有C语言背景.对不起,如果我的问题是“天真”、“太简单”或“工作不够”。
在下面的代码中,我希望针对未来的问题,通过“set”数据结构删除特定的行。但是,首先:它无法匹配删除设置的内容。
另外,第二个问题是o/p中的错误。这可以通过使缩进块工作来检查。
裁剪后的数据文件是:marks_trim.csv
"Anaconda系统校园安置“,,, “于:”、“2011年2月30日”、“ "Sno“、"Math”、"CS“、"GK”、"Prog“、"Comm”、"Sel“ 1,"NA","NA","NA",4,0,0
import csv, sys, re, random, os, time, io, StringIO
datfile = sys.argv[1]
outfileName = sys.argv[2]
outfile = open(outfileName, "w")
count = 0
removal_list = set()
tmp = list()
i=0
re_pattern = "\d+"
with open(datfile, 'r') as fp:
reader1 = csv.reader(fp)
for row in reader1:
if re.match(re_pattern, row[0]):
for cols in row:
removal_list.add(tuple(cols)) #as tuple is hashable
print "::row>>>>>>",row
print "::removal_list>>>>>>>>",removal_list
convert = list(removal_list)
print "<<<<<<<<<<<<<<<<>>>>>>>>>>>>>>>>"
print convert
f = open(datfile, 'r')
reader2 = csv.reader(f)
print ""
print "Removal List Starts"
print removal_list
print "Removal List Ends\n"
new_a_buf = io.BytesIO() # StringIO.StringIO() : both 'io' & StringIO' work
writer = csv.writer(new_a_buf)
rr =""
j = 0
for row in reader2:
if row not in convert: # removal_list: not used as list not hashable
writer.writerow(row) #outfile.write(new_a_buf)
'''
#below code using char array isn't used as it doesn't copy structure of csv file
for cols in row: #at indentation level of "if row not in convert", stated above
if cols not in convert: # removal_list: not used as list not hashable
for j in range(0,len(cols)):
rr+=cols[j] #at indentation level of "if cols not in convert:"
outfile.write(rr) # at the indentation level of 'if'
print "<<<<<<<<<<<<<<<<", rr
f = open(outfile, 'r')
reader2 = csv.reader(f)
'''
new_a_buf.seek(0)
reader2 = csv.reader(new_a_buf)
for row in reader2:
print row
问题/发行
o/p中的常见错误(即使用char数组/ csv.writer对象)也给出了要删除的行,即在removal_list
中出现的行。
但是,在使用char数组检索左行的方法中,错误是:
回溯(最近一次调用): 文件"test_list_in_set.py",第51行 F=打开(外部文件,'r') TypeError:胁迫到Unicode:需要字符串或缓冲区,找到文件
发布于 2014-11-23 08:53:49
我没有读过所有的代码,但它似乎大多不相关。这个错误与打开一个文件有关:open
接受一个文件名,但是您要传递它outfile
,它已经是一个文件了。您应该先关闭该文件,然后通过outfileName
打开。
发布于 2014-11-23 13:19:01
明白了可悲的是我自己。除了改变不存储indl。cols,将removal_list更改为数组,然后使用> removal_list.append(行)追加到数组中。
命中!
https://stackoverflow.com/questions/27086640
复制相似问题