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
添加回答
舉報