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.
Related
I have started my code and am on at a very good start, however, I have come to a road block when it comes to adding sum, average, minimum, and maximum to my code, I'm sure this is a pretty easy fix to someone who knows what there are doing. Any help would be greatly appreciated. The numbers in my file are 14, 22, and -99.
Here is my code so far:
def main ():
contents=''
try:
infile = openFile()
count, sum = readFile(infile)
closeFile(infile)
display(count, sum)
except IOError:
print('Error, input file not opened properly')
except ValueError:
print('Error, data within the file is corrupt')
def openFile():
infile=open('numbers.txt', 'r')
return infile
def readFile(inf):
count = 0
sum = 0
line = inf.readline()
while line != '':
number = int(line)
sum += number
count += 1
line = inf.readline()
return count, sum
def closeFile(inF):
inF.close()
def display(count, total):
print('count = ', count)
print('Sum = ', total)
main()
In the while line!=' ': statement, it will iterate one-one single element in the file, i.e. it will add 1+4 and break the loop when we get " " according to your example. Instead, you can use .split() function and use for loop. Your code (Assuming that all numbers are in a single line):
def read_file():
f=open("numbers.txt","r")
line=f.readline()
l=[int(g) for g in line.split(",")] #there should be no gap between number and comma
s=sum(l)
avg=sum(l)/len(l)
maximum=max(l)
minimum=min(l)
f.close()
return s, avg, maximum, minimum
read_file()
Your code contains a number of antipatterns: you apparently tried to structure it OO-like but without using a class... But this:
line = inf.readline()
while line != '':
number = int(line)
sum += number
count += 1
line = inf.readline()
is the worst part and probably the culprit.
Idiomatic Python seldom use readline and just iterate the file object, but good practices recommend to strip input lines to ignore trailing blank characters:
for line in inf:
if line.strip() == '':
break
sum += number
count += 1
Could anybody advice me if there is any way to keep file pointer in the nested IF clause.
I have to parse the file, and based on its content, different code blocks should process the file.
I came up with nested IF loops.
The code:
import re
with open('smartctl.txt', 'r') as file:
line = file.readlines()
for x in line:
matchIP = re.search('Checking', x)
if matchIP:
print(x)
Match_Micron55 = re.search('Micron_5100', x)
Match_Intel = re.search('INTEL', x)
Match_Micron600 = re.search('Micron_M600', x)
Any_Micron = re.search('Micron', x)
if Match_Micron55:
print("here we have Micron55")
elif Match_Intel:
print("here we have Intel")
elif Match_Micron600:
print('here we have Micron 600')
mline = line
print("file is open")
check = ""
for y in mline:
if y == x:
check == True
continue
if y.startswith(' 1 Raw_Read_Error_Rate') and check == True:
print(y)
continue
if y.startswith(' 5 Reallocated_Sector_Ct') and check == True:
print(y)
continue
if y.startswith('173 Unknown_Attribute') and check == True:
print(y)
break
elif Any_Micron:
print('Here we have unsorted values')
As you can see I read the file as line.
Then I go with variable X through the file.
Then, when I fall in IF condition, I have to CONTINUE reading the file: that's keep the file pointer and continue reading exactly from the place I went into the IF loop. I use 2 loops here with X and Y variables (for x in line and for y in mline). Could you tell me please if I can continue reading the same file in the second(nested) If confidition?
The method seems to be non working. Apart from creating Y variable I have also tried using X in the nested IF clause but was not succeed. The x (line) variable seems to not keep its value on the second IF entry.
I suspect your problem lies in the following code:
line = file.readlines()
for x in line:
The fileread is returning a line from the file, the x in line is iterating through the line a character at a time. I bvelieve you should restructure your code as follows:
replace:
with open('smartctl.txt', 'r') as file:
line = file.readlines()
for x in line:
with:
with open('smartctl.txt', 'r') as file:
for x in file.readlines():
Currently learning python, what I need to do is set the limit of a for loop equal to the int version of the first item read in a file
for example:
if a file contains the list:
10
1
2
3
4
...
I want the first line which contains 10, as the end limit for a for loop.
or maybe there is another way to accomplish this, that would also be appreciated.
here is what i have code:
otherFile = input("Do you have a file to open? (Y/N): ")
while(otherFile == 'Y' or otherFile == 'y'):
totalSum = 0
try:
with open(input("which file would you like to open? "), "r") as file:
for line in file:
totalSum += int(line)
print(line, end="")
print()
print("Total Sum is: ", totalSum)
except FileNotFoundError:
print("File name invalid, Please enter valid name.")
print()
except ValueError:
print("Invalid data type within file.")
otherFile = input("Do you have another file to open? (Y/N): ")
print("Goodbye")
I tried to read only the first line and turning that into an int, then setting it to limit but it did not work, i show that below:
with open(input("which file would you like to open? "), "r") as file:
numLines = int(file.readline())
for line in numLines: <---------- #what I tried
totalSum += int(line)
print(line, end="")
print()
print("Total Sum is: ", totalSum)
Do not cast string into int if you need a list you may create an integer list like this
integers="10 20 30 40"
integers = list(map(int,integers.split(" ")))
Following code can be useful for setting the limit for range
x=fh.readline()
limit_to_set=int(x.split(" ")[0])
for i in range(0,limit_to_set):
# perform your operation
# just showing what is in this file
>>> with open('file_1', 'r') as f:
... for line in f:
... print(line.rstrip())
...
2
abc
def
ghi
jkl
# print only 2 lines
>>> with open('file_1', 'r') as f:
... for _ in range(int(next(f))):
... print(next(f).rstrip())
...
abc
def
If you do it this way and there is a file where the number in the first line is greater than the total number of lines, you will have to handle the StopIteration on your own.
One way would be to write a code like this:
import pandas as pd
df = pd.read_csv('test.txt', delimiter = ' ')
num = df.columns[0]
num here is the integer you are seeking, than you can run your loop like this:
for i in range(num):
when dealing with integers you should use range()
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()
I want to print out a specific line of text base on user input. So far I have this:
list = open("/Users/nicejojo12/Desktop/Python/DictionaryDefinitions.txt")
listo = list.read()
nlines = 0
x = raw_input()
x.lower()
x.capitalize()
if listo.find(x) != -1:
linesr = listo.index(x)
defines = list.readlines(linesr)
print defines
print linesr
else:
print "Nope!"
But when I tried it out, the line number was wrong and it didn't print out anything. This gave no error or anything so I don't know what's wrong.
How do you make a program that opens and reads a specific line of text from a text file based on user input?
A more pythonic approach would be this:
search = raw_input().lower().capitalize()
with open("/Users/nicejojo12/Desktop/Python/DictionaryDefinitions.txt") as datafile:
for line in datafile:
if search in line:
print line
break
else:
print 'Line not found'
Open the file with with so it will be closed automatically .
Don't read the whole file into memory. Just iterate over the lines.
Find the text with in
First, don't use list as a variable name. You're shadowing the builtin function list.
data_file = open("/Users/nicejojo12/Desktop/Python/DictionaryDefinitions.txt")
Second, don't read the file with read(), read it with readlines() as you'd really prefer lines.
lines = data_file.readlines()
line_no = int(raw_input("Gimme a line number:"))
try:
print lines[line_no]
except IndexError:
print "Nope"
First problem: x.lower() and x.capitalize() do not change the string. There is no way to change a string in Python. You can only create new strings. x.lower() and x.capitalize() create new strings. If you want x to be a name for the new string, you need to do that yourself:
x = x.lower().capitalize()
Second problem: Once you have read in the entire file with listo = list.read(), you are at the end of the file. Attempting to read from the file again will not read any more, so defines = list.readlines(linesr) cannot read anything.
listo = list.read()
.After you do this.the list pointer to the file reached the end of file.So
list.readlines()
again will not work unless you do
list.seek(0)
to bring the pointer at the start of file again.
If you are giving text as input then the following way will be useful
list = open("/Users/nicejojo12/Desktop/Python/DictionaryDefinitions.txt")
listo = list.readlines()
nlines = 0
x = raw_input()
x.lower()
x.capitalize()
for sentences in listo:
if x in sentences:
print sentences
Here is a simple way to achieve what you desire (Assuming you want to print all the lines starting with the sting you provide as input):
datalist = open("/Users/nicejojo12/Desktop/Python/DictionaryDefinitions.txt")
listo = datalist.readlines()
nlines = 0
x = raw_input()
x = x.lower()
x = x.capitalize()
for y in list0:
if y.startswith(x):
print y
Here are some small things which you should have in mind:
Do not set list as a variable name as it is a builtin function
x.lower() or x.capitalize() doesn't change x. It just returns a modified version of the string. In order re-use the modified string, set it up as a variable and then use it.
list.readlines(linesr) gives the the number of bytes that have to be read from the file and NOT the line at the index linesr
list = open("/Users/nicejojo12/Desktop/Python/DictionaryDefinitions.txt")
listo = list.read()
lines = listo.split("\n")
nlines = 0
x = raw_input()
x.lower()
x.capitalize()
if len(lines)>int(x):
defines = lines[int(x)-1]
print x
print defines
else:
print "Nope!"
try this code.
First, it will print the line number that you enter from the shell,
after that it will print the specified line of the file.(e.g if x is 3, it will print the 3. line of the document)
Never use built_in_ function names as variable names.
file_1 = open("/Users/nicejojo12/Desktop/Python/DictionaryDefinitions.txt.txt")
listo = file_1.readlines()
line_number = raw_input()
for lines in range(len(listo)):
if int(line_number) == lines:
print listo[lines]
else:
print "enter a line number between 1 to ", len(listo)
break
If you're expecting line numbers as user_input, this will fetch you the respective line from file.