且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用Python检查文件中是否存在数组

更新时间:2022-10-23 08:10:19

您已经在如何使用Python将文本文件转换为数组? [ ^ ]

I have a txt file like this : A1B2C3D4.8Z
I have an array data : ["A1", "xx", "ss", "11"]

I am going to check each 2 character from my txt file whether my array data exist in that file or not.

What I have tried:

I already try to convert my text data to 2D and cut the 3 last characters. Now, I can not figure out how to check the array data exist or not. Here my code.

<pre lang="Python">

outfile = "Result.txt"
Array = ["6J", "xx", "ss", "11"]

with open("test.txt", "r") as f:
	with open(outfile, "w") as result:
		output_list = []
		for rec in f.read().splitlines():
			rec = rec[:-3]  
			list = [rec[i:i+2] for i in range(0, len(rec), 2)] 
			output_list.append(list)

		for line in list:
			found = bool(Array.search(line))
			result.write(str((0,1)[found]))

You have been given suggestions for this issue already at How to convert a text file to array using Python?[^]