【发布时间】:2021-12-19 04:27:56
【问题描述】:
我想知道从表格文本中删除行(同时保留标题)的最佳方法是什么,以便只有包含单词的特定条目采用表格格式。
例如,我有一个包含动物及其名称和年龄的表格文本文件。 (标题是动物/名称/年龄。)如何删除所有在“动物”标题中没有“狗”的行?
动物名称年龄
狗皮平 10
狗快乐 14
狗佛罗多 12
猫索伦 11
鸟甘道夫 10
鸟魔多 12
我只想要: 动物名称年龄
狗皮平 10
狗快乐 14
狗佛罗多 12
我的示例代码如下:
import os
headers = 1
field1 = 'ANIMALS'
sep = ' '
def getIndex(delimString, delimiter, name):
'''Get position of item in a delimited string'''
delimString = delimString.strip()
lineList = delimString.split(delimiter)
index = lineList.index(name)
return index
infile = 'C:/example'
outfile = 'C:/folder/animals'
try:
with open(infile, 'r') as fin:
with open(outfile, 'w') as fout:
for i in range(headers):
line = fin.readline()
fout.write(line)
line = fin.readline()
fout.write(line)
# This is where I get confused, I try using the method below:
for line in fin:
lineList = line.split(sep)
# But the code doesn't work as it only prints the header
# I have a feeling it's the way I'm phrasing this area
if field1 == 'DOG':
fout.write(line)
print '{0} created.'.format(outfile)
except IOError:
print "{0} doesn't exist- send help".format(infile)
在表格 .txt 文件中选择性地打印项目的最佳方法是什么?
【问题讨论】:
-
它可能只是一个 .txt 文件,也可能是一个 .csv 文件?
-
在代码中包含数据而不是我们没有的硬编码路径会很有帮助。否则,在包含数据和代码方面做得很好。使用表格格式,您似乎需要空格分隔值和新行分隔记录。
-
我猜它可以是 txt 或 CSV 文件,都可以。而且我只是在上面的表格文本中使用上面的代码编写一个示例,因为我一直在创建自己的提示。
-
在您的代码中,您将每一行拆分为
lineList,然后继续检查一些变量field1,您将其定义为'ANIMALS'- 因为'ANIMALS' == 'DOG'永远不是True,没有写其他行。相反,if lineList[0] == 'DOG':将是您所追求的。
标签: python file indexing output txt