【问题标题】:Python compare bombs if files not sorted如果文件未排序,Python会比较炸弹
【发布时间】:2013-12-10 20:39:48
【问题描述】:

我编写了一些代码来通过搜索字符串比较两个文件。

文件 = 主数据文件 检查文件 = 州和地区列表

当我在文件中有超过 1 个未按排序顺序排列的状态时,它会爆炸。

我怎样才能让它工作而不必对我的“文件”进行排序

错误消息:回溯(最近一次调用最后一次): 文件“./gangnamstyle.py”,第 27 行,在 csvLineList_2 = csv2[lineCount].split(",") IndexError: 列表索引超出范围

我的代码:

#!/usr/bin/python

import csv
file = raw_input("Please enter the file name to search: ") #File name
checkfile = raw_input("Please enter the file with the search data: ") #datafile
save_file = raw_input("Please enter the file name to save: ") #Save Name
search_string = raw_input("Please type string to search for: ") #search string
#row = raw_input("Please enter column text is in: ") #column number - starts at 0
#ID_INDEX = row
#ID_INDEX = int(ID_INDEX)
f = open(file)
f1 = open(save_file, 'a')
csv1 = open(file, "r").readlines()
csv2 = open(checkfile, "r").readlines()


#what looks for the string in the file
copyline=False
for line in f.readlines():
 if search_string  in line:
  copyline=True
  if copyline:
    f1.write(line)

for lineCount in range( len( csv1) ):
    csvLineList_1 = csv1[lineCount].split(",")
    csvLineList_2 = csv2[lineCount].split(",")
    if search_string == csvLineList_2[0]:
    f1.write(csvLineList_2[2])



f1.close() #close saved file
f.close() #close source file
#csv1.close()
#csv2.close()

【问题讨论】:

  • 它“爆炸了”。错误信息是什么,发生在哪一行?
  • 这是错误:回溯(最近一次调用最后一次):文件“./gangnamstyle.py”,第 27 行,在 csvLineList_2 = csv2[lineCount].split(",") IndexError: 列表索引超出范围

标签: python csv


【解决方案1】:

好的,因此错误消息是csvLineList_2 = csv2[lineCount].split(",") 行中的IndexError: list index out of range。那里只有一个索引,所以显然lineCount 对于 csv2 来说太大了。

lineCount 是 range(len(csv1)) 的值之一。这使得它自动在 csv1 的范围内。显然 csv1 和 csv2 的长度不同,导致 IndexError。

现在这很有可能,因为它们包含来自不同文件的行。显然这些文件的行数不相等。

说实话,我完全不知道您为什么要将这些行读入 csv1。您遍历这些行并将它们拆分(到变量csvLineList_1),但您从不使用该变量。

我认为你的循环应该是:

for line in csv2:
    parts = line.strip().split(",")  # line.strip() removes whitespace and the newline
                                     # at the end of the line
    if search_string == parts[0]:
        f1.write(parts[2] + "\n")  # Add a newline, you probably want it

我希望这会有所帮助。

【讨论】:

  • 谢谢,效果很好..我只需要弄清楚如何让每一行都有项目......现在我得到:DC,22,2,109%,0.64 DC,44,4,218% ,12.1 DC,1231,12,12%,12 DC,131,121,11%,11 Region1 我希望有 DC,131,121,11%,11 - Region1 DC,1231,12,12%,12 - Region1 全部打开当然是新行 - 我发布时格式不正确
  • 还有什么是python的行数限制..一个文件有52个,一个文件有54个
【解决方案2】:

您遇到的错误可能是由于文件长度不相等。

从您所写的内容中并不清楚您希望做什么。在我看来(也许)您想在“主文件”中查找搜索词,如果找到,请将您找到的行写入“保存文件”。在我看来,您还想在“检查文件”的第一个字段中找到相同的搜索词,如果找到,请将第三个字段的内容写入“保存文件”。如果这是错误的,那是因为您的代码有错误。

无论哪种方式,您发布的代码中都存在许多问题,您可能至少会从使用 csv 模块来完成您想做的事情中获得一些好处。

也许发布更完整的问题描述。

编辑:

import csv
import sys

def build_state_lookup(fn):
    with open(fn) as infile:
        reader = csv.reader(infile)
        # throw away first line
        reader.next()
        # now build a dictionary mapping state to region
        lookup = {state: region for (state, _, region) in reader}
        return lookup

def process_big_file(in_fn, checkfile, out_fn):
    lookup = build_state_lookup()
    with open(in_fn) as infile:
        with open(out_fn, 'w') as outfile:
            reader = csv.reader(infile)
            writer = csv.writer(outfile)


            # output the header row
            writer.writerow(reader.next() + ['Region'])
            for row in reader:
                state = row[0]
                region = lookup.get(state, "No Region Found")
                row.append(region)
                writer.writerow(row)


def main():
    process_big_file(*sys.argv[1:])


if __name__ == '__main__':
    main()

【讨论】:

  • RemcoGerlich 帮了大忙。与他的答复.. 文件分别是 55 和 52 行。在我扩展到更大的文件之前,这只是一个测试。我想做的是“文件”检查文件中有状态,项目,人,方差,天数,状态,Full_State_Name,区域。我想要做的是,当他们在“搜索字符串”(例如 DC)中输入状态代码时,它会带回所有 DC 行,行后带有区域名称。所以在文件中你可能有 DC,12345678,John,4%,5 而在检查文件中你有所有的州,比如 DC、哥伦比亚特区、Region1
  • 所以我认为你有两个文件,你想将它们加入“状态”并从一个文件输出所有内容,从另一个文件输出区域?
  • 我添加了一个完整的解决方案,它可能满足您的需求。请询问有关它的问题。 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-01-17
  • 2016-02-09
  • 1970-01-01
  • 1970-01-01
  • 2021-09-10
  • 2013-11-04
  • 1970-01-01
相关资源
最近更新 更多