2 回答
TA贡献1820条经验 获得超2个赞
即使您想使用替代分隔符(即 而不是 ),使用csv模块仍然是一个好主意。它将更好地产生格式良好的输出。\t,
下面是一个示例:
import csv
import io
# Representing csvRows as a 2D array, hopefully approximating your input.
csvRows = [
['0', '0', '30', 'Testing Unit', 'True', 'COMP_PC', 'COMP_PC'],
['0', '0', '30', 'Prod Unit', 'True', 'ASSM_UL', 'ASSM_UL'],
]
# Using a StringIO instance to capture the output, alternatively you
# can easily write to a file.
results = io.StringIO()
writer = csv.writer(results, delimiter='\t')
# Process your data.
for row in csvRows:
if any('PC' in value for value in row):
writer.writerow(row)
# Print the results.
output = results.getvalue()
print(output)
# Use repr() to verify that each line is terminated with '\r\n'.
print(repr(output))
输出:
$ python3 example.py
0 0 30 Testing Unit True COMP_PC COMP_PC
'0\t0\t30\tTesting Unit\tTrue\tCOMP_PC\tCOMP_PC\r\n'
TA贡献1735条经验 获得超5个赞
想通了,正如Furas所说:
"PC" in string可以检查“PC”是否是更长字符串的一部分。 检查列表中是否有确切的字符串“PC” - 但它无法检查“PC”是否是此列表中较长字符串的一部分。"PC" in list
只需要迭代列表并检查那里。
for csvRow in reader(csvRows[2:]):
for csvValue in csvRow:
if "PC" in csvValue:
for csvValue2 in csvRow:
values += csvValue2 + "\t"
values = values[:-1] + "\r\n"
break
else:
continue
添加回答
举报