【问题标题】:Python TypeError: coercing to Unicode: need string or buffer, file foundPython TypeError:强制转换为 Unicode:需要字符串或缓冲区,找到文件
【发布时间】:2014-11-23 07:33:02
【问题描述】:

我喜欢学习 Python,具有 C 语言背景。抱歉,如果我的问题是“幼稚”、“太简单”或“不够有效”。

在下面的代码中,我想练习未来的问题,通过“集合”数据结构删除特定行。但是,首先:它无法匹配删除集的内容。

另外,第二个问题:是o/p中的错误。这可以通过使缩进块工作来检查。

修剪后的数据文件为:ma​​rks_trim.csv

“Anaconda Systems 校园布局”,,,,,,,

“于:”,,,“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 数组检索遗漏行的方法中,错误是:

Traceback(最近一次调用最后一次):

文件“test_list_in_set.py”,第 51 行,在

f = open(outfile, 'r')

TypeError:强制转换为 Unicode:需要字符串或缓冲区,找到文件

【问题讨论】:

  • 试着让问题简短而简短..
  • 里亚德所说的。请修复代码示例的格式/缩进。

标签: python


【解决方案1】:

我没有通读所有这些代码 - 但它似乎并不相关。该错误与打开文件有关:open 采用文件名,但您将其传递给 outfile,这已经是一个文件。您应该先关闭该文件,然后通过outfileName 打开。

【讨论】:

  • 好的,好的。但是,第一个问题的原因是什么。会有很大帮助。
  • 鉴于我下面的错字更正,能否指出出处。
【解决方案2】:

知道了,很遗憾我自己。 除了不存储 indl 的变化。 cols,将removing_list更改为数组,然后使用>removing_list.append(row)追加到数组

命中!

【讨论】:

    猜你喜欢
    • 2016-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-28
    • 2015-02-01
    • 2014-12-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多