Python Forum
How to check an array exist in a file using Python - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Homework (https://python-forum.io/forum-9.html)
+--- Thread: How to check an array exist in a file using Python (/thread-16282.html)

Pages: 1 2


RE: How to check an array exist in a file using Python - fitrisibarani - Feb-25-2019

Could you please explain it what should I change? and what should it be? THanks


RE: How to check an array exist in a file using Python - ichabod801 - Feb-25-2019

I explained what you should change and where you should change it. It's time for you to try and implement it, and come back to me with any problems you have.


RE: How to check an array exist in a file using Python - fitrisibarani - Feb-26-2019

I tried this one and I got it. But I can not figure out to write the result to a file. Any idea?
FBlist_set = set(FBlist)
Array_set = set (Array)

if Array_set & FBlist_set:
	print ("found")
 	result.write("found") #??????
else:
	print ("Not Found")



RE: How to check an array exist in a file using Python - ichabod801 - Feb-26-2019

If you still want to write out 1's and 0's, you would change line 6 to result.write('1'), and add result.write('0') under the else statement.


RE: How to check an array exist in a file using Python - fitrisibarani - Feb-27-2019

It returns an error with this code
if Array_set & FBlist_set:
	print ("Found")
	result.write("1")
else:
	print ("Not Found")
	result.write("0")
The error is : Traceback (most recent call last):
ValueError: I/O operation on closed file.


RE: How to check an array exist in a file using Python - ichabod801 - Feb-27-2019

I can't diagnose that from the current snippet. Please show your current full code.


RE: How to check an array exist in a file using Python - fitrisibarani - Feb-27-2019

This is all my current code :
infile = "test.txt"
outfile = "Result.txt"
Array = ["6J", "yB", "ss", "11"]

with open(infile, "r") as input_file:
	with open(outfile, "w") as result:
		output_list = []
		for rec in input_file.read().splitlines():
			rec = rec[:-3]  
			FBlist = [rec[i:i+2] for i in range(0, len(rec), 2)] 
			output_list.append(FBlist)
			print(output_list)

FBlist_set = set(FBlist)
Array_set = set (Array)

if Array_set & FBlist_set:
	print ("Found")
	result.write("1")
else:
	print ("Not Found")
	result.write("0")



RE: How to check an array exist in a file using Python - ichabod801 - Feb-27-2019

You need to indent everything from line 14 on twice. When the with clause on line 6 ends (after the indented block below it), the file associated with 'result' closes, and you can't access it anymore. So you need to indent the rest of the code to be under that with clause.