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文件中查询
例如我的数据在一个csv文件设置是如下
名字性别年龄
约翰米15
玛丽F 13
SAM米12
在名称的用户的输入(即萨姆),我希望能够导出整行数据(即“sam,m,12”)作为数据并将其导出为.txt文件。
如果我想指出山姆的性别,例如,我该如何去做呢? 此外,如何正确使用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
我会去了解一下标准库的[CSV](https://docs.python.org/3/library/csv.html)模块。它提供了一个方便的'reader()'对象,它包含可以下标的列表列表(即按列索引)。 – pstatix
甚至是'DictReader',它使用列标题作为字典键 – Adirio
嗨,莎拉,请检查我的答案,并问我你需要什么,我会尽力帮助。 –