Python - read numbers from text file in a function

Python - read numbers from text file in a function

By : user2953100
Date : November 19 2020, 03:59 PM
To fix this issue I'm trying to write a program that ensures to write on a text file finding prime numbers between given number and limit. If the number exists in file, It tries to write another number which is coprime with the given(entered) number. Then it is written on the text file. My problem is checking numbers from text file whether exist or not. How can I write it ? So, I have researched since the morning but, I can't find helpful answers for the problem. I think Python quite a change works from C. , presuming all nums are all on separate lines like below:
code :

from fractions import gcd

def coprime(n1, n2):
    return gcd(n1, n2) == 1 # same as if gcd(n1, n2) == 1:return True else: return False

with open("out.txt","a+") as f: # with automatically closes your files
    # add all previous numbers into a set, casting to int using map 
    # map(int, f)  equivalent to [int(ele) for ele in f] in python2
    nums_set = set(map(int, f)) # with 1 5 and 7 in the file nums_set = set([1, 5, 7])
    i = 0
    j = 0

    num = int(raw_input("Please enter number "))
    limit = int(raw_input("Please enter limit "))

    while i < limit:
        if j not in nums_set and coprime(num,j):
            print "{} is written on the text file.".format(j)
            i += 1
            j += 1
            # add current j's from this run to the set to avoid reopening and rechecking he file        
            j += 1

Share : facebook icon twitter icon
How to read numbers in text file using python?

How to read numbers in text file using python?

By : Busy Buzzy Bee
Date : March 29 2020, 07:55 AM
fixed the issue. Will look into that further I am new to python programming and I am learning python by doing simple programs. Here is what I would like to do: if I have a text file containing numbers: say this a f1.txt , You could do it like this:
code :
a1 = []
a2 = []
a3 = []
a4 = []

with open('f1.txt') as f:
    for line in f:
        data = line.split()
a = [[], [], [], []] # A list with four empty lists
for i, value in enumerate(line.split()):
read numbers from text file python

read numbers from text file python

By : user2592799
Date : March 29 2020, 07:55 AM
To fix the issue you can do I am trying to read a text file and return the contents of the text file. The textfile contains a matrix. When i run my code with the file it just prints the first line. My code looks right and i have searched online and cant seem to find the problem.
code :
while line != "":
    return line # function ends
while line != "":
    print line
How to read numbers in text file as numbers in to list in python?

How to read numbers in text file as numbers in to list in python?

By : joe458
Date : March 29 2020, 07:55 AM
help you fix your problem I have a text file in which there are numbers in each line(only numbers).it my color.txt look like , just cast your strings into integers:
code :
How to read numbers in a text file for python?

How to read numbers in a text file for python?

By : dbf30
Date : March 29 2020, 07:55 AM
To fix the issue you can do I'm writing a program where I'm doing simple calculations from numbers stored in a file. However, it keeps on returning a ValueError. Is there something I should change in the code or how the text file is written? , If you can't read a line, skip to the next one.
code :
for line in in_file:
        donation = float(line)
    except ValueError:
with open("donations.txt", "r") as in_file:
    highest = lowest = donation = None
    number = total = 0
    for line in in_file:
            donation = float(line)
        except ValueError:
        if highest is None or donation > highest:
            highest = donation

        if lowest is None or donation < lowest:
            lowest = donation

        number += 1
        total += donation

        average = total / number

print "The highest amount is $%.2f" %highest
print "The lowest amount is $%.2f" %lowest
print "The total donation is $%.2f" %total
print "The average is $%.2f" %average
Can't read numbers from a text file in python

Can't read numbers from a text file in python

By : bnu
Date : March 29 2020, 07:55 AM
like below fixes the issue So this is just one way to take all of your values and calculate the average.
code :
input_file = input("enter file name: ") 
open_file = open(input_file, 'r') 
grades_list = []
for grade in open_file:
    grade_format = grade.strip()    #how to remove extra blank space
grade_convert = []    #new list for all of the converted values
for grade in grades_list:
    convert = float(grade)     #convert each value in the list into a float
grade_convert = sorted(grade_convert)    #very first element will be the lowest
grade_convert.pop(0)    #permanently removes the very first item

grade_total = 0    #set a counter
for grade in grade_convert:    
    grade_total += grade    #add all of the values to the counter

grade_average = grade_total / len(grade_convert)    #len is number of items 
Related Posts Related Posts :
  • How to perform cartesian product with Tensorflow?
  • Multiple independent random number streams from single seed
  • I Need a simple and short python3 code that count secounds in a background process
  • No module named constants
  • from django 1.4 to django 1.5- argument 'verify_exists' what s replacement?
  • Slash replacement inside a raw string
  • Reordering columns/rows of a pivot_table?
  • MySQLdb.cursors.Cursor.execute does not work
  • Python module being reimported when imported at different places
  • Is the Session object from Python's Requests library thread safe?
  • Python Regex: Finding First and Last Names
  • Order by selection in List view of OpenERP 7.0
  • Reading input values in ipython notebook
  • List of dictionaries - how to read a specific value in a dictionary
  • writing os.system output to file
  • Create dictionary from points list and multiple attribute lists
  • How to write a table line by line with for loop
  • Map projection and forced interpolation
  • Django FBV's "render_to_response" equivalent in Class-Based-View?
  • Paramiko raises "SFTPError: Garbage packet received"
  • python pandas operations on columns
  • python list appending is not working
  • Speeding up matplotlib scatter plots
  • For each element of the list find closest date from a different list
  • How to prepend new rows at the beginning of an existing csv file?
  • how to make database robust to process kills with sqlite postgress and sqlalchemy?
  • finding a set of ranges that a number fall in
  • New line in python print() function
  • How to clear os.environ value for only one Variable in Python
  • Why does python append a modulo(%) operator to the end of a newly opened file?
  • recursive function or non-recursive that doesnt use 2 ** approach
  • Extract floats from a String using regular expression
  • How to solve: ImportError: No module named django.core.wsgi in Apache2 log?
  • What's the most concise way to include multiple statements in a Python switch case?
  • python xml pretty print not working
  • Can we use NumPy in writing a website?
  • Called bashscript doesn't start up GNU screen session
  • Reading fortran direct access data and writing formatted data - faster with python than with fortran?
  • Language supporting nested definition of functions
  • Find elements which exists in the most of the lists
  • Templating library in node.js similar to Jinja2 in Python?
  • Python Syntax Error, 'break' is outside the loop
  • Replacing spaces with hyphens
  • How to open a csv file in Microsoft Excel in Python?
  • ModuleNotFoundError: No module named 'users'
  • Interpolating with multiple y-values
  • Import warning PACKAGE.egg is added to sys.path
  • Is there a key for the default namespace when creating dictionary for use with xml.etree.ElementTree.findall() in Python
  • Using fill_between() with a Pandas Data Series
  • How to build a lookup table for tri-linear interpolation in NumPy?
  • Matrix vector multiplication along array axes
  • Can a cookiejar object be pickled?
  • __init__.py in project folder breaks nose tests
  • Comparing times with sub-second accuracy
  • advanced search using HayStack + Solr in Django?
  • Base test case class for python unittest
  • The PyData Ecosystem
  • Finding unique entries with oldest time stamp
  • Custom filesize format with Python Humanize?
  • Use `tf.image.resize_image_with_crop_or_pad` to resize numpy array
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org