I need to sum numbers in a file [closed] - python

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Ok I'm learning read and write files at the moment but I need a little help to sum the numbers in a file.
def main ():
sample = open (r'C:\user\desktop\text.txt','r')
for i in range (the range of int is unknown)
file = sample.read ()
sample.close ()
main ()

You may iterate over the file like this:
for i in sample:
and convert using int() to an integer.
The for loop can be done with map and the sum with sum.
This is the final code:
def main ():
sample = open (r'C:\user\desktop\text.txt','r')
result = sum(map(int, sample))
print(result)
sample.close ()
main ()

What you want is:
for line in sample:
# process the line
If each line just contains an integer, you can simplify it further to sum(map(int, sample)).

To add safety, you should cast your integers with error checking and ensure that the file exists before reading it.
import os
def safecast(newtype, val, default=None):
try:
return newtype(val)
except ValueError:
pass
return default
def sumfile(filename):
if not os.path.isfile(filename):
return None
sum = 0
with open(filename, "r") as file:
for line in file:
sum += safecast(int, line, 0)
return sum
sum = sumfile(r'C:\user\desktop\text.txt')
print(sum)

Related

Creating functions to read file in python [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 months ago.
Improve this question
This a sample txt file called "price_file.txt":
Apple,$2.55
Banana,$5.79
Carrot,$8.19
Dragon Fruit,$8.24
Eggs,$1.44
Hamburger Buns,$1.89
Ice Pops,$4.42
This is a function to allow the user to read the file:
def addpricefile (price_file):
# input: price file txt
# output: item mapped to its price in a dictionary
global item_to_price
for next_line in price_file:
item,price = next_line.strip().split(',')
item_to_price[item]= float(price[1:]) #map item to price
return item_to_price
p = input ("Enter price file: ")
price_file2 = open(p, "r")
price_file = price_file2.readlines()
for next_line in price_file:
addpricefile(price_file2)
print(item_to_price)
price_file2.close()
However, I get an empty dictionary as the output. How do I fix this?
Try this code, I was a bit confused by what you had there but you can simplify the operation a bit. This will achieve the same result. I hope this helps you solve your problem.
def openAndSeperate(filename):
with open(filename,'r') as file:
priceList = {}
for i in file:
i = i.strip('\n').split(',')
priceList[i[0]] = float(str(i[1])[1:])
return priceList
def main():
filename = 'price_file.txt'#input('Enter File Name: \n')
priceList = openAndSeperate(filename)
print(priceList)
if __name__ == '__main__':
main()

Cannot pass values from one def to another, says too many values to unpack [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I honestly do not know what to do. The questions I got on StackOverflow were about strings and csv inputs, but these variables I am expecting are different. Help would be very much appreciated. I always get ValueError: too many values to unpack (expected 3). I want the code to pass the three returned variables from speedCalc() to something I could use in the calculations in spellCheck() (line 35). What should I do?
Here's the code:
#!/usr/bin/env python
import time
import random
import string
import sys
import string
import sys
#from getkey import getkey
def generateTest():
mylines = []
with open ('phrases.txt', 'rt') as myfile: # Open phrases.txt for reading the typing tests
for line in myfile: # For each line of text,
mylines.append(line) # add that line to the list.
# Converting lines of list to select a random phrase
listLen = len(mylines) - 1
return (mylines[random.randint(0,listLen)])
def speedCalc():
# words / time passed (assuming it is 5)
start = time.time()
test = input(print(generateTest()))
end = time.time()
timePassed = (end - start)
generateTestLen = len(generateTest())
return test
return timePassed
return ((generateTestLen/5)/timePassed)*60
def spellCheck():
test, timePassed, wpm = speedCalc()
diff = 0
correctChars = 0
file_A = generateTest()
file_B = test
read_A=open(file_A,'r').read()
read_B=open(file_B,'r').read()
for char_a, char_b in zip(read_A, read_B):
if char_a == char_b:
correctChars = correctChars+1
read_A_len = len(read_A)
correctPercent = (correctChars/read_A_len)*100
errors = read_A_len - correctChars
errorRate = errors/timePassed
netWPM = wpm - errorRate
return correctPercent
return netWPM
correctPercent, netWPM = spellCheck()
print(netWPM)
Instead of using:
return test
return timePassed
return ((generateTestLen/5)/timePassed)*60
use
return test, timePassed, ((generateTestLen/5)/timePassed)*60
Your function as you defined in your example just returnes test and exits then. The second and third return is not executed any more.
When a return statement is reached, a function stops. Any code after the return statement is never executed.
The code
return test
return timePassed
return ((generateTestLen/5)/timePassed)*60
is equivalent to
return test
You should return a tuple of three values. Use
return test, timePassed, ((generateTestLen/5)/timePassed)*60
Adjust spellCheck accordingly, it has the same problem.

ValueError: invalid literal [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
This post was edited and submitted for review 4 days ago.
Improve this question
def _init_(self. row, col, data):
self.child = {}
self.row = row
self.col = col
self.data = data
self.active = True
file = open('filename.txt', 'r')
maze = file.readlines()
n = (intmaze[0])
full = maze[1:(n*n)+1]
file.close
Value error: invalid literal for int() with base 10:'2,1,1,3\n'
I am trying to read a text file with the following matrix
2,1,1,3
2,1,2,3
1,1,2,3
3,G,3,1
You have replace n = int(maze[0]) with the following ->
You have to first store it into list by l = maze.split(",") then you can write n = len(l) to get the length of the matrix.
with open("maze.txt","r") as fd:
maze = [i.split(",") for i in fd.read().splitlines()]
print(len(maze[0]))
print(maze)

There is no output from file.write [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 3 years ago.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Improve this question
I run the following program and expect to get the output in a .txt file.
I have run this in spyder IDE with python 3.6.
temperatures = [10,-20,-289,100]
file = open('temperature.txt','w')
def f_to_c(temperatures):
for celsius in temperatures:
if celsius > -273.15:
fahrenheit = celsius * (9/5) + 32
file.write(str(fahrenheit))
f_to_c(temperatures)
There is no error message in this code, but I didn't get the output in the .txt file. Can you help?
Updated function and explanation:
def f_to_c(file: str, temps: list):
with open(file, 'a', newline='\n') as f:
for temp in temps:
if temp > -273.15:
fahrenheit = temp * (9/5) + 32
f.write(f'{fahrenheit}\n')
temps = [10,-20,-289,100]
f_to_c('temperature.txt', temps)
Use with open, opens the file, only when the function is called.
The specific reason you never get any output in your file, is because file is never closed.
Using with, will automatically close the file. Reading and Writing Files
Opening the file inside the function, means you won't be looking to the outer scope, to find the file object. Scope of Variables in Python
Use a to append to the file, each time the function is called.
f'{fahrenheit}\n' is an f-string.
PEP 498 -- Literal String Interpolation
Using the f-string, there's no need to convert fahrenheit, using str()
(file: str, temps: list) uses PEP 484 - Type Hints
Alternatively:
Have a dedicated function for converting the temperatures.
This is the appropriate way do deal with the task.
Functions should do one thing.
Deal with the file separately
def f_to_c(temps: list) -> list:
return [temp * (9/5) + 32 for temp in temps if temp > -273.15]
temps = [10,-20,-289,100]
with open('temperature.txt', 'a', newline='\n') as f:
for value in f_to_c(temps):
f.write(f'{value}\n')
The function is implemented with List Comprehensions
The return statement
A cleaner approach below
def f_to_c(temperatures):
fahrenheit_results = []
for celsius in temperatures:
if celsius > -273.15:
fahrenheit_results.append(celsius * (9 / 5) + 32)
return fahrenheit_results
results = f_to_c([10, -20, -289, 100])
with open('out.txt','w') as out:
for r in results:
out.write(str(r) + '\n')

Reading data from txt file only reads last line [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I'm trying to print data from my text file into python
text_file = open ("Class1.txt", "r")
data = text_file.read().splitlines()
for li in data:
namelist = li.split(":")[0]
scorelist = li.split(":")[1]
print (namelist)
print (scorelist)
text_file.close()
My text file has:
Jim:13524
Harry:3
Jarrod:10
Jacob:0
Harold:5
Charlie:3
Jj:0
It only shows the last entry
Shell:
Would you like to view class 1, 2 or 3? 1
Jj
0
The problem is that you are over-writing the value of namelist and scorelist with each pass through the loop. You need to add each item to a list. Adding a sequential list of items to a list is usually done with list.append() or a list comprehension. Read the documentation, or do some tutorials?
To actually create list, you can do this:
namelist, scorelist = [],[]
for li in data:
namelist.append(li.split(":")[0])
scorelist.append(li.split(":")[1])
Alternately, this might be a better overall approach:
with open("Class1.txt", "r") as text_file:
names_scores = [(e[0],e[1]) for e in [li.split(":") for li in text_file]
for name,score in name_scores:
print(name,score)
This assumes you really just want to extract the names and scores and print them, not do anything else. How you handle and store the data depends a lot on what you are doing with it once you extract from the file.

Categories