I'm writing a function that sums up integers from a file.
Here's the code:
def sum_integers_from_file(file_name):
try:
file = open(name)
total = 0
for i in file:
total += int(i)
file.close()
return total
except:
print "error"
file foo.txt:
1234
The function returns 1234.
why doesn't total += int(i) add up all the integers?
It is highly recommended to read files in a with statement. That frees you from the responsibility of closing the file and is also shorter! This works:
def sum_integers_from_file(file_name):
try:
with open(file_name, 'r') as f:
s = f.read()
total = 0
for char in s:
total += int(char)
return total
except:
print("error")
Your file has one line.
You're adding all ints from each line.
If you want to add 1,2,3,4 with that method move them to new lines
Also, you can do the same thing with this
with open(name) as f:
return sum(int(line) for line in f)
Related
I have a code that i am writing to read a txt file and report sum, average, ect... but I also need it to recognize when the txt file is empty or has no numbers in it, and not crash. i have tried os.stat(f).st_size == 0, and os.path.getsize(f) == 0:, and reading the first character too. for some reason my code is not picking up on the exception and keeps continuing on with the rest of the code and then crashes when trying to divide by zero to find the average. I am also not using any external libraries.
#the below code asks for the file name and opens the file :)
while (True):
try:
filename = input("What file would you like to acess?: ")
f = open(filename, "r")
except IOError:
print("File", filename, "could not be opened")
except:
if os.path.getsize(f) == 0:
print("There are no numbers in", filename)
else:
break
#the below line displays the file name :)
print("File Name: ", f.name)
#the below code calculates the sum and prints it :)
sum=0
for n in f:
n=n.strip()
sum=sum+int(n)
print("Sum: ", sum)
#the below code calculates the number of lines and prints it :)
with open(filename, "r") as f:
count = 0
for line in f:
if line != "\n":
count += 1
print("Count: ", count)
#the below code calculates the average and prints it :)
avg = sum/count
print("Average: ", avg)
I am trying to read all the lines in a specific file, and it prints the number of the line as an index.
What I am trying to do is to delete the line by inputting the number of the line by the user.
As far as it is now, it prints all the lines with the number of that line, but when I enter the number of the line to be deleted, it's not deleted.
This is the code of the delete function:
def deleteorders ():
index = 0
fh = open ('orders.txt', 'r')
lines = fh.readlines()
for line in lines:
lines = fh.readlines()
index = index+1
print (str(index) + ' ' + line)
try:
indexinp = int(input('Enter the number of the order to be deleted, or "B" to go back: '))
if indexinp == 'B':
return
else:
del line[indexinp]
print (line)
fh = open ('orders.txt', 'w')
fh.writelines(line)
fh.close()
except:
print ('The entered number is not in the range')
return
This should work (you'll need to add the error handling back in):
lines = enumerate(open('orders.txt'))
for i, line in lines:
print i, line
i = int(input(">"))
open('orders.txt', 'w').write(''.join((v for k, v in lines if k != i)))
I'm trying to create a function that accepts a file as input and prints the number of lines that are full-line comments (i.e. the line begins with #followed by some comments).
For example a file that contains say the following lines should print the result 2:
abc
#some random comment
cde
fgh
#another random comment
So far I tried along the lines of but just not picking up the hash symbol:
infile = open("code.py", "r")
line = infile.readline()
def countHashedLines(filename) :
while line != "" :
hashes = '#'
value = line
print(value) #here you will get all
#if(value == hashes): tried this but just wasn't working
# print("hi")
for line in value:
line = line.split('#', 1)[1]
line = line.rstrip()
print(value)
line = infile.readline()
return()
Thanks in advance,
Jemma
I re-worded a few statements for ease of use (subjective) but this will give you the desired output.
def countHashedLines(lines):
tally = 0
for line in lines:
if line.startswith('#'): tally += 1
return tally
infile = open('code.py', 'r')
all_lines = infile.readlines()
num_hash_nums = countHashedLines(all_lines) # <- 2
infile.close()
...or if you want a compact and clean version of the function...
def countHashedLines(lines):
return len([line for line in lines if line.startswith('#')])
I would pass the file through standard input
import sys
count = 0
for line in sys.stdin: """ Note: you could also open the file and iterate through it"""
if line[0] == '#': """ Every time a line begins with # """
count += 1 """ Increment """
print(count)
Here is another solution that uses regular expressions and will detect comments that have white space in front.
import re
def countFullLineComments(infile) :
count = 0
p = re.compile(r"^\s*#.*$")
for line in infile.readlines():
m = p.match(line)
if m:
count += 1
print(m.group(0))
return count
infile = open("code.py", "r")
print(countFullLineComments(infile))
I am working with the results from infra sound detectors but sometimes they have glitches so the data points are recorded as '0'. This is worthless data. I want to be able to search the file for '0', count them and print out that result.
All I have been able to do so far is search the file for '0' and get a true/false answer.
This is my code:
def findzero( fname ):
if os.path.isfile(fname):
f = open( fname )
s = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)
if s.find('0') != -1:
print 'true'
else:
print ''
return;
Scan the file line by line, counting the lines with just '0':
def countzero(fname):
try:
with open(fname) as f:
return sum(line.strip() == '0' for line in f)
except IOError:
# not a file we can read
return None
The Python bool type is a subclass of int, and True is equal to 1, False is 0, so you can sum the booleans to get a count.
If you needed a percentage, you need to count lines and 0-counts separately:
def count_zeros_and_lines(fname):
try:
with open(fname) as f:
zeros = total = 0
for line in f:
if line.strip() == '0':
zeros += 1
total += 1
return zeros, total
except IOError:
# not a file we can read
return None
This returns a count of zeros, and a total line count.
Essentially what I am attempting to do is read 'n' number of lines from a file and then write them to a separate file. This program essentially should take a file that has 100 lines and separate that file into 50 separate files.
def main():
from itertools import islice
userfile = raw_input("Please enter the file you wish to open\n(must be in this directory): ")
file1 = open(userfile, "r+")
#print "Name: ", file1.name
#print "Closed or not", file1.closed
#print "Opening mode: ", file1.mode
#print "Softspace flag: ", file1.softspace
jcardtop = file1.read(221);
#print jcardtop
n = 2
count = 0
while True:
next_n_lines = list(islice(file1,n))
print next_n_lines
count = count + 1
fileout = open(str(count)+ ".txt", "w+")
fileout.write(str(jcardtop))
fileout.write(str(next_n_lines))
fileout.close()
break
if not next_n_lines:
break
I do have the file printing as well to show what is in the variable next_n_lines.
*['\n', "randomtext' more junk here\n"]
I would like it instead to look like
randomtext' more junk here
Is this a limitatoin of the islice function? Or am I missing a portion of the syntax?
Thanks for your time!
Where you call str() or print, you want to ''.join(next_n_lines) instead:
print ''.join(next_n_lines)
and
fileout.write(''.join(next_n_lines))
You can store the flattened string in a variable if you don't want to call join twice.
Did you mean something like this?
f = open(userfile,"r")
start = 4
n_lines = 100
for line in f.readlines()[start:(start + n_lines)]:
print line
#do stuff with line
or maybe this rough, yet effective code:
f = open(userfile,"r")
start = 4
end = start + 100
count = start
while count != end:
for line in f.readlines()[count:(count + 2)]:
fileout = open(str(count)+ ".txt", "w+")
fileout.write(str(line))
fileout.close()
count = count + 2