I am trying to count all numbers in given file. It works unless there is a word between a numbers.
e.g:
1
2
car
3
4
Here's my code:
def main():
count=0
with open("numbers.txt", "r") as f:
try:
line = f.readline()
while line != '':
print(line.strip())
count += int(line)
line = f.readline()
except Exception as err:
print(err)
print(count)
main()
I was thinking about continue, but it does only work with for or while. So is there any way?
You should move the try and except blocks inside your loop. Then when you hit a line with a non-number, you'll just skip it and go on the the next line.
Unrelated to that error, you can also simplify your code a bit by iterating over the file directly in a for loop, rather than calling readline repeatedly in a while loop:
with open("numbers.txt", "r") as f:
for line in f: # simpler loop
print(line.strip())
try: # move this inside the loop
count += int(line)
except Exception as err: # you may only want to catch ValueErrors here
print(err)
print(count)
you can use isdigit to check for number:
while line != '':
print(line.strip())
if line.strip().isdigit():
count += int(line.strip())
line = f.readline()
Here is Pythonic way to achieve this
if you want to sum all digit:
f = open('file')
total_count = sum(int(x) for x in f if x.strip().isdigit())
if you want to count how many of them are digit:
f = open('file')
total_digit = len(x for x in f if x.strip().isdigit())
You can use the isdigit method to check if the line contains only numbers:
def main():
count=0
with open("numbers.txt", "r") as f:
count = sum(int(line) for line in f if line.strip().isdigit())
print(count)
if __name__ == '__main__':
main()
You can try using regular expressions:
import re
total = 0
with open("numbers.txt", "r") as f:
line = f.readline()
while line != '':
total += sum([int(x) for x in re.findall('(\\d+)', line)])
line = f.readline()
print total
Related
So, I'm doing this assignment and I can't seem to figure out how to continue on to the next step.
assignment output example
The file numbers.txt contains the following numbers all on separate lines (25, 15, 5, six, 35, one, 40).
My problem is that I can only print out one ValueError message (six), but I need to be able to print out both messages (invalid literal for int() with base 10: 'six\n', invalid literal for int() with base 10: 'one\n').
Since I can't get the codes to move on to the next iteration, my average only adds 25, 15, and 5.
I've only been learning Python for a month so I don't know if there's a simple way to solve all these problems.
Below is the code I am working on.
def main():
while True:
try:
filename = input("Enter a file name: ")
infile = open(filename, "r")
except IOError:
print("[Error No. 2] No such file or directory:", filename)
continue # continue to next iteration
else:
break
data = infile.readline().strip()
numbers = data.split()
total = 0
count = 0
try:
infile = open(filename, "r") #somehow without this, the first line won't print
for line in infile:
num = int(line)
print(num)
total += num
count += 1
print("The average is: ", total/count)
except ValueError as err:
print(err)
finally:
print(total/count)
main()
You can repositioning your try statement in the second loop like so:
data = infile.readline().strip()
numbers = data.split()
total = 0
count = 0
infile = open(filename, "r")
for line in infile:
try:
num = int(line)
print(num)
total += num
count += 1
except ValueError as err:
print(err)
print("The average is: ", total/count)
This way, you won't exit the loop once you encounter an error message, and will simply print it and move on to the next line.
Try the below
# open the file using 'with' - it will make sure that the file will be closed
with open('input.txt') as f:
values = []
# read the lines into a list
lines = [l.strip() for l in f.readlines()]
for line in lines:
# try to convert to int
try:
x = int(line)
values.append(x)
except ValueError as e:
print(e)
# calculate the average
print(f'Avg: {sum(values)/len(values)}')
input.txt
25
15
5
six
35
one
40
output
invalid literal for int() with base 10: 'six'
invalid literal for int() with base 10: 'one'
Avg: 24.0
You need to indent your while True as currently the main function is causing an error.
You should also do an if line == ‘six’:
line = 6
You can set the try-except block inside the for loop which should produce the correct results.
data = infile.readline().strip()
numbers = data.split()
total = 0
count = 0
infile = open(filename, "r")
for line in infile:
try:
num = int(line)
total += num
count += 1
except ValueError as err:
print(err)
print("The average is: ", total/count)
This is the code to search a particular entry in a file:
num2find = str(input("Enter a number to find: "))
test_file = open("testfile.txt", "r")
num = "0"
flag = False
while (num != ""):
num = test_file.readline()
if (num == num2find):
print("Number found.")
flag = True
break
if not flag:
print("\nNumber not found.")
The test file is:
1
2
3
4
5
If I input 2, the code still outputs "Number not found."
Every time you read a line from a text file, you are getting "\n" at the end of the string line, so the problem you are facing is that you are comparing "2" to "2\n" which is not the same.
You could take advantage of with to pen your file. This way you do not need to worry about closing the file once you are done with it. Also, you do not need to pass the "r" argument since it is the default mode for open.
You should use a for loop instead of that needless while loop. The for loop will terminate automatically when all the lines in the file have been read.
One more improvement you could make is to rename the flag flag to found, and to print the result once the file has been processed.
num2find = int(input("Enter a number to find: "))
found = False # rename flag
with open("testfile.txt") as test_file: # use with to avoid missing closing the file
for line in test_file: # use a for loop to iterate over each line in the file
num = int(line)
if num == num2find:
found = True
break
if found: # print results at the end once file was processed
print("Number found.")
else:
print("Number not found.")
Each line in the test file contains two characters - the number and a newline. Since "2" does not equal "2\n", your number is not being found. To fix this, use the int function to parse your lines, since it ignores whitespace (like the \n) character:
num2find = int(input("Enter a number to find: "))
flag = False
with open("testfile.txt", "r") as test_file:
for line in test_file:
num = int(line)
if num == num2find:
print("Number found.")
flag = True
break
if not flag:
print("\nNumber not found.")
The easiest and the most logical solution I could come up with after all the feedback was this:
num2find = int(input("Enter a number to find: "))
file_data = open("testfile.txt", "r")
found = False
for data in file_data:
if int(data) == num2find:
found = True
if found:
print("\nNumber found.")
else:
print("\nNumber not found.")
file_data.close()
You need to add .rstrip() on num = test_file.readline()
Try something like this:
num2find = str(input("Enter a number to find: "))
test_file = open("testfile.txt", "r")
file_data = test_file.readlines()
flag = False
for item in file_data:
if num2find == item.rstrip():
flag = True
break
if not flag:
print("\nNumber not found.")
else:
print("Number found")
Don't use .readline() like that, use readlines() instead
I have been using python for some time, I have a file that is the english alphabet with each word on separate lines, and I have ironed out all the errors, but it doesn't type anything anymore. I'm open to any help, and improvements to the code, provided you explain how it works. If you are looking for the file it is here
f = open("C:\\my folders\\brit-a-z.txt", 'r')
print("Type in your cloze word like this: cl-z-")
def cloze(word):
for line in f:
match = True
if len(line) == len(word):
for i in range(len(word)):
if not word[i] == "-":
if line[i] == word[i]:
match == False
if match == True:
print(line)
while True:
cloze(input())
Once you've iterated through the file for the first word, the file closes. You'll need to save f. For example:
with open("C:\\my folders\\brit-a-z.txt", 'r') as f:
f = f.read().splitlines()
I am making a program that lets you edit, or read a text document in python, and I'm not finished yet, and I'm stuck on the reading part. I want it to print only one line, and I'm drawing a blank on how to do so. The read part is in "def read():"
def menu():
print("What would you like to do?")
print("\n(1) Write new text")
print("(2) Read line 3")
choice = float(input())
if choice == 1:
write()
elif choice == 2:
read()
def read():
with open('test.txt', 'r') as read:
print()
def write():
print("\nType the full name of the file you wish to write in.")
file1 = input().strip()
with open(file1, "a") as add:
print("What do you want to write?")
text = input()
add.write("\n"+ text)
menu()
def read():
with open('test.txt', 'r') as f:
for line in f:
print(line)
Edit:
def read():
with open('test.txt', 'r') as f:
lines = f.readlines()
print lines[1]
You can use the file as an iterable, and loop over it, or you can call .next() on it to advance one line at a time.
If you need to read 1 specific line, this means you can skip the lines before it using .next() calls:
def read():
with open('test.txt', 'r') as f:
for _ in range(2):
f.next() # skip lines
print(f.next()) # print the 3rd line
I figured mine out pretty late since i do not use the 'def' function, but this prints out the line that you want to print
import os.path
bars = open('bars.txt', 'r')
first_line = bars.readlines()
length = len(first_line)
bars.close()
print(first_line[2])
fileName = raw_input("Enter the filename: ")
n = input("Enter the line you want to look: ")
f = open(fileName,'r')
numbers = []
for line in f:
sentenceInLine = line.split('\n')
for word in sentenceInLine:
if word != '':
numbers.append(word)
print numbers
print len(numbers)
print numbers[n-1]
if n == 0:
print "There is no 0 line"
break
i think you missed to split sentenceInLine like sentenceInLine.split(' ')
You are looping over each line, then you split lines based on '\n'. That \n is a line break character. That would confuse your logic right there.
So it is a bit confusing what you are trying to do but you should check n after the user has inputed a value for n. not at the end.
You may want to also catch the exception where file cannot be found I think this is what you need:
fileName = raw_input("Enter the filename: ")
n = input("Enter the line you want to look: ")
if n == 0:
print "There is no 0 line"
sys.exit();
try:
f = open(fileName,'r')
except IOError:
print "Could not find file"
sys.exit()