Adding Up Numbers From A List In Python - python

basically i'm trying to complete a read file. i have made the "make" file that will generate 10 random numbers and write it to a text file. here's what i have so far for the "read" file...
def main():
infile = open('mynumbers.txt', 'r')
nums = []
line = infile.readline()
print ('The random numbers were:')
while line:
nums.append(int(line))
print (line)
line = infile.readline()
total = sum(line)
print ('The total of the random numbers is:', total)
main()
i know it's incomplete, i'm still a beginner at this and this is my first introduction to computer programming or python. basically i have to use a loop to gather up the sum of all the numbers that were listed in the mynumbers.txt. any help would be GREATLY appreciated. this has been driving me up a wall.

You don't need to iterate manually in Python (this isn't C, after all):
nums = []
with open("mynumbers.txt") as infile:
for line in infile:
nums.append(int(line))
Now you just have to take the sum, but of nums, of course, not of line:
total = sum(nums)

The usual one-liner:
total = sum(map(int, open("mynumbers.txt")))
It does generate a list of integers (albeit very temporarily).

Although I would go with Tim's answer above, here's another way if you want to use readlines method
# Open a file
infile = open('mynumbers.txt', 'r')
sum = 0
lines = infile.readlines()
for num in lines:
sum += int(num)
print sum

Just another solution... :-)
with open("x.txt") as file:
total = sum(int(line) for line in file)
This solution sums the "results" of a generator object so it isn't memory intensive yet short and elegant (pythonic).

Related

Concatenate number into a list of text in Python

I'm trying to concatenate some numbers into a text list using Python. This is my code
import hashlib
def SHA1_hash(string):
hash_obj = hashlib.sha1(string.encode())
return(hash_obj.hexdigest())
with open("/Users/admin/Downloads/Project_files/dictionary.txt") as f:
n = 5
numtext_list = []
for i in range(0,n+1):
for j in f:
numtext = j.strip() + str(i)
numtext_list.append(numtext)
print(numtext_list)
However, it only concatenates the first number (which is 0) to the file elements, and the output list is like this:
'yellow0', 'four0', 'woods0', 'hanging0', 'marching0', 'looking0', 'rouse0', 'lord0', 'sagde0', 'meadows0', 'sinking0', 'foul0', 'bringing0', 'disturb0', 'uttering0', 'scholar0', 'wooden0'
While I want it to also have
'yellow1', 'yellow2', 'yellow3', 'yellow4', 'yellow5','four0',...
as well as other combinations of text and numbers to the list.
Please help me with this, I'm totally new to Python so please excuse me if this is not a good question or I am wrong in writing keywords, thank you so much.
The first time you do for j in f: you read the entire file. So when you get to the next iteration of the for i loop, there's nothing left to read, so the inner loop ends immediately and nothing is appended.
Swap the order of your loops so you only have to read the file once.
for j in f:
word = j.strip()
for i in range(0, n+1):
numtext = f'{j}{i}'
numlist.append(numtext)
Other possible solutions:
Read the file into a list with f.readlines() and then loop over that.
Put f.seek(0) before each for j in f: loop.

Troubles averaging all the grades from a "CSV" file

So I am new to python and I am having a hard time figuring this code. I am trying to use "CSV File" called exam_grades.csv and then write a function that reads in all my values in the file but using the string class split() method to split this long string into a list of strings. Each string represents a grade. Then my function should return the average of all the grades.
So far this is what I have; I can open the .csv file just fine but I'm having troubles averaging all the grades. I have some commented out because I am sure where to go from what I have been doing :(
def fileSearch():
'Problem 4'
readfile = open('exam_grades.csv', "r")
for line in readfile:
l = line.split(str(","))
#num_grades = len(l)
#averageAllGrades = l * 500
#return num_grades
print(l)
fileSearch()
Any advice?
Thanks!
Most CSV files have a header at the top, you'll want to skip that but for simplicity sake, let's say we ignore that.
Here's some code that works:
def fileSearch():
'Problem 4'
readfile = open('exam_grades.csv', "r")
grade_sum = 0
grade_count = 0
for line in readfile:
l = line.split(str(","))
for grade in l:
grade_sum += int(grade)
grade_count += 1
print(grade_sum/grade_count)
fileSearch()
This assumes you have multiple lines with grades and multiple grades per line.
We're keeping track of two variables here, the sum of all grades and the number of all grades we've added to the list (we're also casting to integers, since you're going to be reading strings).
When you add all the grades up and divide by the number of grades, you get an average.
Hope this helped.

Dividing a .txt file in multiple parts in Python

I'm a begginer in Python, and I have a question about file reading :
I need to process info in a file to write it in another one. I know how to do that, but it's reaaally ressource-consuming for my computer, as the file is really big, but I know how it's formatted !
The file follows that format :
4 13
9 3 4 7
3 3 3 3
3 5 2 1
I won't explain what it is for, as it would take ages and would not be very useful, but the file is essentialy made of four lines like these, again and again. For now, I use this to read the file and convert it in a very long chain :
inputfile = open("input.txt", "r")
output = open("output.txt", "w")
Chain = inputfile.read()
Chain = Chain.split("\n")
Chained = ' '.join(Chain)
Chain = Chained.split(" ")
Chain = list(map(int, Chain))
Afterwards, I just treat it with "task IDs", but I feel like it's really not efficient.
So do you know how I could divide the chain into multiple ones knowing how they are formatted?
Thanks for reading !
How about:
res = []
with open('file', 'r') as f:
for line in f:
for num in line.split(' '):
res.append(int(num))
Instead of reading the whole file into memory, you go line by line.
Does this help?
If you need to go 4 lines at a time, just add an internal loop.
Regarding output, I'm assuming you want to do some computation on the input, so I wouldn't necessarily do this in the same loop. Either process the input once reading is done, or instead of using a list, use a queue and have another thread read from the queue while this thread is writing to it.
Perhaps the utility of a list comprehension will help a bit as well (I doubt this will make an impact):
res = []
with open('file', 'r') as f:
for line in f:
res.append( int(num) for num in line.split() )
hmm there's some method to write to a file without reading it i believe
Add text to end of line without loading file
https://docs.python.org/2.7/library/functions.html#print
from __future__ import print_function
# if you are using python2.7
i = open("input","r")
f = open("output.txt","w")
a = "awesome"
for line in i:
#iterate lines in file input
line.strip()
#this will remove the \n in the end of the string
print(line,end=" ",file=f)
#this will write to file output with space at the end of it
this might help, i'm a newbie too, but with better google fu XD
Maybe do it line by line. This way it consumes less memory.
inputfile = open("input.txt", "r")
output = open("output.txt", "a")
while True:
line = inputfile.readline()
numbers = words.split(" ")
integers = list(map(int, numbers))
if not line:
break
There is probably a newline character \n in the words. You should also replace that with an empty string.
If you don't wanna to consume memory (you can run of it if file is very large), you need to read lien by line.
with open('input.txt', 'w') as inputfile, open('"output.txt', 'w') as output:
for line in inputfile:
chain = line.split(" ")
#do some calculations or what ever you need
#and write those numbers to new file
numbers = list(map(int, chain))
for number in numbers
output.write("%d " % number)

I am learning Python, need some pushing in the right direction

I am trying to learn Python through Coursera, and have some questions about an assignment.
Write a program that prompts for a file name, then opens that file and reads through the file, looking for lines of the form:
X-DSPAM-Confidence: 0.8475
Count these lines and extract the floating point values from each of the lines and compute the average of those values and produce an output as shown below. Do not use the sum() function or a variable named sum in your solution.
My code so far is as follows:
fname = raw_input("Enter file name: ")
f = open(fname)
for line in f:
if not line.startswith("X-DSPAM-Confidence:") : continue
print line
print "Done"
I am a bit confused. Should I store each line I get into a file or variable or something and then extract the floating point values for each?
How should this be tackled in the simplest way since this is just the beginning of the course?
Here is a code snippet that suffices your work. I am reading the float values from the line with "X-DSPAM-Confidence:" and adding them and in the end, I am taking the mean. Also, since you are a beginner, I suggest to keep in mind that when you are dealing with division and you are expecting a float, either numerator or denominator should be float to give the answer in float. Since in the below code snippet, our number is float, we wont have that issue.
fname = raw_input("Enter file name: ")
f = open(fname)
cnt = 0
mean_val = 0
for line in f:
if not line.startswith("X-DSPAM-Confidence:") : continue
mean_val += float(line.split(':')[1])
cnt += 1
f.close()
mean_val /= cnt
print mean_val
The reason not to use a variable named sum is because there is a function with the same name.
The assignment asks you to do the work of the sum() function explicitly. You are on the right track with the if not line but might be more successful if you reverse the logic (like this: if line.startswith ...), then put the handling inside an indented block that follows.
The handling you need is to keep track of how many such lines you handle and the accumulated sum. Use a term that is a synonym for sum that is not already a Python identifier. Extract the float value from the end of line and then <your sum variable> += float(the float from "line").
Don't forget to initialize both counter and accumulator before the loop.
with open(fname) as f:
s = 0
linecount = 0
for line in f:
l = line.split()
try:
num = float(l[1])
except ValueError:
continue
if l[0] == 'X-DSPAM-Confidence:':
s += num
linecount += 1
print(s/linecount)
Here's how I would do it. I'll happily answer any questions.
Using Regular expression.
More info regarding re module, check here !!!
Code:
import re
fname = raw_input("Enter file name: ")
f = open(fname)
val_list = []
tot = 0
line_cnt = 0
for line in f:
a = re.findall("X-DSPAM-Confidence:\s*(\d+\.?\d*)",line)
if len(a) != 0:
tot += float(a[0])
line_cnt +=1
print ("Line Count is ",line_cnt)
print ("Average is ",tot/line_cnt)
f.close()
Content of y.txt:
a
X-DSPAM-Confidence: 0.8475
b
X-DSPAM-Confidence: 0.8476
c
X-DSPAM-Confidence: 0.8477
d
X-DSPAM-Confidence: 0.8478
Output:
C:\Users\dinesh_pundkar\Desktop>python c.py
Enter file name: y.txt
Line Count is 4
Average is 0.84765
C:\Users\dinesh_pundkar\Desktop>
Points:
You can open file using with as Patrick has done in his answer. If file is opened using with then no need to close the file explicit.

how to create a list and sum up

I am relatively new to python and got stuck on the below:
Below is the code I am working with
import re
handle = open ('RegExWeek2.txt')
for line in handle:
line = line.rstrip()
x = re.findall('[0-9]+', line)
if len(x) > 0:
print x
The return from this code looks like this:
['7430']
['9401', '9431']
['2248', '2047']
['5517']
['3184', '1241']
['9939']
['2185', '9450', '8428']
['369']
['3683', '6442', '7654']
Question: how do I combine this to one list and sum up the numbers?
Please help
You may change your code like this,
handle = open ('RegExWeek2.txt')
num = []
for line in handle:
num.extend(re.findall('[0-9]+', line))
print sum(int(i) for i in num)
Since you're using re.findall, this line.rstrip() line is not necessary.
And also there won't be possible for x to be an empty list, since we are using + next to [0-9] (repeats the previous token one or more times) not * (zero or more times)
There's no need to rstrip, and you should open files using with:
import re
all_numbers = []
with open('RegExWeek2.txt') as file:
for line in file:
numbers = re.findall('[0-9]+', line)
for number in numbers:
all_numbers.append(int(number))
print(sum(all_numbers))
This is really beginner code, and a direct translation of yours. Here's how I would write it:
with open('RegExWeek2.txt') as file:
all_numbers = [int(num) for num in re.findall('[0-9]+', file.read())]
print(sum(all_numbers))

Categories