Reading a file until a match found with python - python

I have been trying this code to loop through randomly until a match found in the lookin.txt file and stop when a match is found with no success as my Python knowledge not that brilliant. Code is working only once but i need it to run continously until it finds a match. I appreciate if someone can direct me in the right direction.
#! /usr/bin/env python
import random
randrange = random.SystemRandom().randrange
z = randrange( 1, 1000)
target_f = open("lookin.txt", 'rb')
read_f = target_f.read()
if z in read_f:
file = open('found.txt', 'ab')
file.write(z)
print "Found ",z
else:
print "Not found ",z
Lookin.txt:
453
7
8
56
78
332

you need to use while and change the random number:
#!/usr/bin/env python
import random
target_f = open("lookin.txt", 'rb')
read_f = target_f.read()
while True: # you need while loop here for looping
randrange = random.SystemRandom().randrange
z = str(randrange( 1, 1000))
if z in read_f:
file = open('found.txt', 'ab')
file.write(z)
file.close()
print "Found ",z
break # you can break or do some other stuff
else:
print "Not found ",z

import random
running=True
while running:
a=random.randint(1,1000)
with open ("lookin.txt") as f:
rl=f.readlines()
for i in rl:
if int(i)==a:
print ("Match found")
with open("found.txt","w") as t:
t.write(str(a))
running=False
Try this.Also with open method is better for file processes. If you want to only one random number, than you can just put the a variable outside of while loop.

The "z = randrange(1,1000)" gives you one random number and the rest of your script reads the entire file and tries to match that number against the file.
Instead, enclose place the script into a loop for it to keep trying.
import random
randrange = random.SystemRandom().randrange
while True:
z = randrange( 1, 1000)
DO YOUR SEARCH HERE
The while True will cause your script to run forever so depending on what you are trying to accomplish, you'll need to add an "exit()" someplace for when you want the program to end.
Also, your "if z in read_f" line fails because it expects a string and not the integer value from the random number generator. Try "if str(z) in read_f:"

We can get only integer value from target file(used with statement to read file) and create dictionary which get constant time for key search.
Apply while loop to find random number into file i.e. in created dictionary.
If random number found in the dictionary then add to found.txt and break code.
If not found random number then continue for next random number.
import random
randrange = random.SystemRandom().randrange
with open("lookin.txt", 'rb') as target_f:
tmp = [int(i.strip()) for i in target_f.read().split('\n') if i.isdigit() ]
no_dict = dict(zip(tmp, tmp))
while 1:
z = randrange( 1, 1000)
if z in no_dict:
with open('found.txt', 'ab') as target_f:
target_f.write("\n"+str(z))
print "Found ",z
break
else:
print "Not found ",z
Note: If target file not contains any integer in between random number range then code will go into infinite loop.

Related

How to read an input file of integers separated by a space using readlines in Python 3?

I need to read an input file (input.txt) which contains one line of integers (13 34 14 53 56 76) and then compute the sum of the squares of each number.
This is my code:
# define main program function
def main():
print("\nThis is the last function: sum_of_squares")
print("Please include the path if the input file is not in the root directory")
fname = input("Please enter a filename : ")
sum_of_squares(fname)
def sum_of_squares(fname):
infile = open(fname, 'r')
sum2 = 0
for items in infile.readlines():
items = int(items)
sum2 += items**2
print("The sum of the squares is:", sum2)
infile.close()
# execute main program function
main()
If each number is on its own line, it works fine.
But, I can't figure out how to do it when all the numbers are on one line separated by a space. In that case, I receive the error: ValueError: invalid literal for int() with base 10: '13 34 14 53 56 76'
You can use file.read() to get a string and then use str.split to split by whitespace.
You'll need to convert each number from a string to an int first and then use the built in sum function to calculate the sum.
As an aside, you should use the with statement to open and close your file for you:
def sum_of_squares(fname):
with open(fname, 'r') as myFile: # This closes the file for you when you are done
contents = myFile.read()
sumOfSquares = sum(int(i)**2 for i in contents.split())
print("The sum of the squares is: ", sumOfSquares)
Output:
The sum of the squares is: 13242
You are trying to turn a string with spaces in it, into an integer.
What you want to do is use the split method (here, it would be items.split(' '), that will return a list of strings, containing numbers, without any space this time. You will then iterate through this list, convert each element to an int as you are already trying to do.
I believe you will find what to do next. :)
Here is a short code example, with more pythonic methods to achieve what you are trying to do.
# The `with` statement is the proper way to open a file.
# It opens the file, and closes it accordingly when you leave it.
with open('foo.txt', 'r') as file:
# You can directly iterate your lines through the file.
for line in file:
# You want a new sum number for each line.
sum_2 = 0
# Creating your list of numbers from your string.
lineNumbers = line.split(' ')
for number in lineNumbers:
# Casting EACH number that is still a string to an integer...
sum_2 += int(number) ** 2
print 'For this line, the sum of the squares is {}.'.format(sum_2)
You could try splitting your items on space using the split() function.
From the doc: For example, ' 1 2 3 '.split() returns ['1', '2', '3'].
def sum_of_squares(fname):
infile = open(fname, 'r')
sum2 = 0
for items in infile.readlines():
sum2 = sum(int(i)**2 for i in items.split())
print("The sum of the squares is:", sum2)
infile.close()
Just keep it really simple, no need for anything complicated. Here is a commented step by step solution:
def sum_of_squares(filename):
# create a summing variable
sum_squares = 0
# open file
with open(filename) as file:
# loop over each line in file
for line in file.readlines():
# create a list of strings splitted by whitespace
numbers = line.split()
# loop over potential numbers
for number in numbers:
# check if string is a number
if number.isdigit():
# add square to accumulated sum
sum_squares += int(number) ** 2
# when we reach here, we're done, and exit the function
return sum_squares
print("The sum of the squares is:", sum_of_squares("numbers.txt"))
Which outputs:
The sum of the squares is: 13242

Use content of .txt file line as input for python3 variable

I have a python script which print in a text file every prime.
I would like my script to pickup the list where it left off so basically take the contents of the last line as a variable.
Here is my current script:
def calc():
while True:
x = 245747
y = (100**100)**100
for n in range (x,y):
if all(n%i!=0 for i in range (2,n)):
a=[]
a.append(n)
fo = open('primes.txt', 'a+')
print(n)
print ("", file = fo)
print ((a), file = fo)
fo.close
s = input('To do another calculation input yes, to quit input anything else...')
if s == 'yes':
continue
else:
break
calc()
I would like the variable x to get as an input the last line of primes.txt
There should be on that last line "[245747]" if the greatest prime number is 245747.
How could I achieve that? Thanks!
You can do use readlines and get the last item of the list:
file = open("primes.txt", "r").readlines()
x = file[len(file)-1]
I think this should work.
You can just get rid of the 2 "[" and "]" with split or something similar.

Python write random integers to file on newline

I need to make a program that generates 10 random integers between 10 and 90 and calls two separate functions to perform separate actions. The first one (playlist) simply needs to print them all on one line without spaces, which was easy. The second one (savelist) is giving me problems. I need to write every number in the list nums to angles.txt with each number on a separate line in order. No matter what I try I can't get them on separate lines and it appears as one string on a single line. What am I missing?
import random
def main():
nums = []
# Creates empty list 'nums'
for n in range(10):
number = random.randint(10, 90)
nums.append(number)
# Adds 10 random integers to list
playlist(nums)
savelist(nums)
def playlist(numb):
index = 0
while index < len(numb):
print(numb[index], end=' ')
index += 1
def savelist(number):
myfile = open('angles.txt', 'w')
# Creates numbers.txt file
number.sort()
myfile.write(str(number) + '\n')
myfile.close()
main()
In savelist(), you need to loop through the list:
myfile = open('angles.txt', 'w')
# Creates numbers.txt file
number.sort()
for e in number:
myfile.write(str(e))
myfile.close()
When you send "nums" to savelist(), you are sending a list. If you just try to write "numbers" to the file, it's going to write the whole list. So, by looping through each element in the list, you can write each line to the file.
To write a list to a file you need to iterate over each element of the list and write it individually, with the attached newline. For example:
def savelist(number):
myfile = open('angles.txt', 'w')
# Creates numbers.txt file
number.sort()
for n in number:
myfile.write(str(number) + '\n')
myfile.close()
You could also generate a single string by joining your list with newlines, and then write that to the file. For example:
myfile.write('\n'.join([str(n) for n in number])
Finally, you may want to consider using a context manager on the file open, to ensure that the file is closed whatever happens. For example:
def savelist(nums):
# Creates numbers.txt file
nums.sort()
with open('angles.txt', 'w') as myfile:
myfile.write('\n'.join([str(n) for n in nums])
Note that I also changed the variable name to nums rather than number ('number' is slightly confusing, since the list contains >1 number!).
Try this code out: You are writing an array as a whole to the file, and therefore are seeing only one line.
def main():
nums = [] # Creates empty list 'nums'
for n in range(10):
number = random.randint(10, 90)
nums.append(number)
# Adds 10 random integers to list
playlist(nums)
savelist(nums)
def playlist(numb):
index = 0
while index < len(numb):
print(numb[index], end=' ')
index += 1
def savelist(number):
myfile = open('angles.txt', 'w')
# Creates numbers.txt file
number.sort()
for element in number:
myfile.write(str(element) + '\n')
myfile.close()
main()
#tomlester already stated that you need to loop through the elements in number. Another way to do this is.
def savelist(number):
number.sort()
with open('angles.txt', 'w') as myfile:
myfile.write('\n'.join(map(str, number)))
Here's how I would do it:
from random import randint
def rand_lst(lo, hi, how_many):
return [randint(lo, hi) for _ in range(how_many)]
def print_lst(nums):
print(''.join(str(num) for num in nums))
def save_lst(nums, fname):
with open(fname, "w") as outf:
outf.write('\n'.join(str(num) for num in sorted(nums)))
def main():
nums = rand_lst(10, 90, 10)
print_lst(nums)
save_lst(nums, "angles.txt")
if __name__ == "__main__":
main()

python read files and stop when a condition satisfies

I am trying a program where it reads all files in a directory and when the 'color=brown' is attained then my program has to stop reading even if finds 'color=brown' in the next file.I mean,the condition first met should only be taken.
I tried a program where it prints all the color=brown from all the files,but i have to stop after its first read. Please help!
import os
path = r'C:\Python27'
data = {}
for dir_entry in os.listdir(path):
dir_entry_path = os.path.join(path, dir_entry)
if os.path.isfile(dir_entry_path):
with open(dir_entry_path, 'r') as my_file:
for line in my_file:
for part in line.split():
if "color=brown" in part:
print part
please help!answers will be appreciated!
you can set a variable stating that you are done and then break out of each loop
but depending on the nesting of the loop it might be cleaner to use an exception to jump out of the loop (kind of like a goto in C):
try:
for m in range(10):
for n in range(10):
if m == 5 and n == 15:
raise StopIteration
except StopIteration:
print "found"
else:
print "not found"
print "always runs unless the other clauses return"
You're looking for the break statement.
...
if "color=brown" in part:
print part
# set some variable to check at the last thing before your other for loops
# turnover.
br = True
break
and then use that to break out of every other two for loops you've initiated.
if br == True:
break
else:
pass
if br == True:
break
else:
pass

Python: Ignoring empty lines when identifying happy numbers

The task (from codeeval) is to read a file that has a few different numbers, and print 1 if it is a happy number or print 0 if it is not a happy number. Part of the task is to ignore the item (num) if it is an empty line. Here is my code:
import sys
test_cases = open(sys.argv[1], 'r')
for num in test_cases:
if num=="":
pass
else:
liszt=[]
while num>1:
newnum=str(num)
total=0
for i in newnum:
total+=int(i)**2
if total not in liszt:
liszt.append(total)
num=total
else:
print 0
break
else:
print 1
test_cases.close()
I get an error message that references the total+=int(i)**2 line, saying this:
ValueError: invalid literal for int() with base 10: ''
Which makes me think I'm not being successful in ignoring empty lines. Am I on the right track? If so, what change should I make to the code?
Thanks for your help!
In order to make sure you don't deal with empty lines and new lines, you can simply add:
if num.strip():
num = num.rstrip('\n')
# DO SOMETHING HERE...
# ...
So you'll get:
import sys
test_cases = open(sys.argv[1], 'r')
for num in test_cases:
if num.strip():
num = num.rstrip('\n')
# DO SOMETHING HERE...
# ...
test_cases.close()

Categories

Resources