如何将匹配条件的数据设为1并写入文件,同时保留原数据完整性
解决方案
首先先明确你的匹配条件列表,将其定义为变量:
headers = [ "query environment variable", "get file size", "read file on Windows", "read file via mapping", "get thread local storage value", "terminate process", "link function at runtime on Windows", "linked against ZLIB" ]
1. 替换匹配项为1并保留其他数据写入文件
不能直接在读取原文件的同时写入,会导致文件内容混乱。正确做法是先读取所有数据到内存,处理后再写入(建议先写入新文件测试,避免误操作覆盖原数据)。
写入新文件(推荐)
import csv headers = [ "query environment variable", "get file size", "read file on Windows", "read file via mapping", "get thread local storage value", "terminate process", "link function at runtime on Windows", "linked against ZLIB" ] # 读取原文件所有内容 with open("your_output3.csv", 'r') as csv_file_obj: reader_obj = csv.reader(csv_file_obj) heading = next(reader_obj) # 读取表头 rows = list(reader_obj) # 读取所有行数据 # 处理每行数据,替换匹配项为1 for row in rows: for i in range(len(row)): if i < 2: continue if row[i] in headers: row[i] = 1 # 写入处理后的内容到新文件 with open("processed_output.csv", 'w', newline='') as new_csv: writer = csv.writer(new_csv) writer.writerow(heading) writer.writerows(rows)
覆盖原文件(谨慎操作)
如果确认要直接修改原文件,只需将写入的文件名改为原文件名即可,但务必先备份原文件。
2. 将匹配到的内容写入另一个文件
在遍历数据时收集所有匹配到的内容,之后写入单独的文件:
import csv headers = [ "query environment variable", "get file size", "read file on Windows", "read file via mapping", "get thread local storage value", "terminate process", "link function at runtime on Windows", "linked against ZLIB" ] matched_items = [] with open("your_output3.csv", 'r') as csv_file_obj: reader_obj = csv.reader(csv_file_obj) next(reader_obj) # 跳过表头 for row in reader_obj: for i in range(len(row)): if i < 2: continue if row[i] in headers: matched_items.append(row[i]) # 将匹配项写入独立文件 with open("matched_content.txt", 'w') as f: for item in matched_items: f.write(f"{item}\n")
合并两个需求的完整代码
如果需要同时完成替换写入和收集匹配项,可以合并代码,避免重复读取文件:
import csv headers = [ "query environment variable", "get file size", "read file on Windows", "read file via mapping", "get thread local storage value", "terminate process", "link function at runtime on Windows", "linked against ZLIB" ] matched_items = [] # 读取原文件数据 with open("your_output3.csv", 'r') as csv_file_obj: reader_obj = csv.reader(csv_file_obj) heading = next(reader_obj) rows = list(reader_obj) # 同时处理替换和收集匹配项 for row in rows: for i in range(len(row)): if i < 2: continue if row[i] in headers: matched_items.append(row[i]) row[i] = 1 # 写入处理后的CSV文件 with open("processed_output.csv", 'w', newline='') as new_csv: writer = csv.writer(new_csv) writer.writerow(heading) writer.writerows(rows) # 写入匹配项到独立文件 with open("matched_content.txt", 'w') as f: for item in matched_items: f.write(f"{item}\n")
内容的提问来源于stack exchange,提问作者jack_dan
相关产品推荐
相关产品推荐

