查询CSV文件

时间:2017-10-05 12:04:18

标签: python file csv field rows

  filename = selectedCompany + "/" + "1" + ".txt"  # define filename to save file with
        for row in csv_file:
            if selectedCompany == row[1]:
                count +=1
                if not os.path.exists(os.path.dirname(filename)):
                    try:
                        os.makedirs(os.path.dirname(filename))
                    except OSError as exc:  # Guard against race condition
                        if exc.errno != errno.EEXIST:
                            raise
        totalCnt=0
        print listOfCompanies #to debug
        print selectedCompany #to debug
        while totalCnt < len(csv_file): # as long as total count is lesser than length of csv file
            totalCnt+=1        # add total count of 1
            for row in csv_file:
                if selectedCompany == row[:][1]: # if selected company equals to the company in csv file
                    with open(filename, "w") as output:  # save the .txt file
                        output.write(str(csv_file[totalCnt])) # save the contents of the csv file
                else:
                    totalCnt+=1  # add total count of 1

大家好,我使用python从csv文件中读取数据并将它们导出为单独的.txt文件。 我的问题是如何引用特定行中的特定字段?

例如,我在csv文件中设置的数据如下

姓名性别年龄
  john m 15
  玛丽f 13
  sam m 12

根据用户输入的名称(即sam),我希望能够将整行数据(即&#34; sam,m,12&#34;)作为数据导出将其导出为.txt文件。

例如,如果我想指出sam的性别,我该如何去做呢? 此外,如何正确使用for循环以确保我可以导出所需的所有必需.txt文件?

我已经尝试过搜索,但是我的情况是一个逻辑错误,并且很难排除故障。

非常感谢任何帮助。

编辑:

使用熊猫模块后出现错误信息:

   File "C:\Python27\lib\site-packages\pandas\core\frame.py", line 1797, in 
    __getitem__
    return self._getitem_column(key)
    File "C:\Python27\lib\site-packages\pandas\core\frame.py", line 1804, in _ 
   getitem_column
    return self._get_item_cache(key)
      File "C:\Python27\lib\site-packages\pandas\core\generic.py", line 1084, in 
    _get_item_cache
    values = self._data.get(item)
      File "C:\Python27\lib\site-packages\pandas\core\internals.py", line 2851, 
    in get
    loc = self.items.get_loc(item)
     File "C:\Python27\lib\site-packages\pandas\core\index.py", line 1572, in 
    get_loc
    return self._engine.get_loc(_values_from_object(key))
     File "pandas\index.pyx", line 134, in pandas.index.IndexEngine.get_loc 
    (pandas\index.c:3824)
     File "pandas\index.pyx", line 154, in pandas.index.IndexEngine.get_loc 
    (pandas\index.c:3704)
     File "pandas\hashtable.pyx", line 686, in p 
    pandas.hashtable.PyObjectHashTable.get_item (pandas\hashtable.c:12280)
      File "pandas\hashtable.pyx", line 694, in pandas.hashtable.PyObjectHashTable.get_item (pandas\hashtable.c:12231)
KeyError: False

1 个答案:

答案 0 :(得分:0)

如果我是你,我会想到Pandas包装 - 使用那个包装你的任务可能非常简单,例如。

import pandas as pd
data = pd.read_csv("CSVFILE.csv", sep=',') # if you have your csv with headers it will create dataframe with names name | gender | age
desiredoutput = data[data.name == USERINPUT] #USERINPUT is e.g. sam (it us up to you how you gain it.. e.g. via input() command)

您的输出也是逗号分隔值((即&#34; sam,m,12&#34;)) 因此您可以轻松地将其保存到csv只包含一行,您可以通过用户输入选择。

desiredoutput.to_csv("NAMEYOUCHOOSE.csv", sep = ",", index=False, header=False)