why does my code "break" out of loop? - python

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()

Related

Why is my code not able to find the input number in the file even if the input number is clearly present in the file?

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

Python outputting contents from file

When I'm running the program it is outputting that no countries exist starting with that letter, when in fact they exist. Can someone tell me what I'm doing wrong or maybe give me an alternate way to only output countries starting with the wanted letter. This is my code:
#Creating the list
CountryList = []
CountryandPopulationList = []
#Creating the Function1
def Function1(fh,letter):
count = 0
#Adding the file to the list
for word in fh:
CountryandPopulationList.append(word)
index = word.find('-')
Country = word[0:index]
CountryList.append(Country.strip())
#Printing countries starting with chosen letter
try:
for i in CountryList:
if(i[1]== letter):
print(i)
count = count + 1
else:
print('The letter does not exist')
except IndexError:
print('Total number of countries starting with letter',letter,'=',count )
#Asking user to input letter
letter = input('Enter the first letter of the country: ')
#Opening the file
try:
fh = open('D:\FOS\\Countries.txt','r')
except IOError:
print('File does not exist')
else:
function1 = Function1(fh,letter)
Thank you
Please also provide the input format of your Countries.txt file as well as the python version you are using s.t. it is easier to help you.
For a start: open() will not provide you with the file content but only gives you the textwrapper object. Try changing the line to
fh = open('D:\FOS\...\Countries.txt', 'r').read()
A slightly simpler version. Try this:
def function1(fh, letter):
count = 0
country_list = [line.split('-')[0].strip() for line in fh.readlines()]
for country in country_list:
if country.lower().startswith(letter.lower()):
count += 1
print(country)
print("Total number of countries starting with letter '%s'= %d" % (letter, count))
#Asking user to input letter
letter = input('Enter the first letter of the country: ')
#Opening the file
try:
with open('D:\FOS\\Countries.txt','r') as fh:
function1(fh, letter)
except IOError:
print('File does not exist')

wrapping text from a file

I am writing a program that will open a specified file then "wrap" all lines that are longer than a given line length and print the result on the screen.
def main():
filename = input("Please enter the name of the file to be used: ")
openFile = open(filename, 'r+')
file = openFile.read()
lLength = int(input("enter a number between 10 & 20: "))
while (lLength < 10) or (lLength > 20) :
print("Invalid input, please try again...")
lLength = int(input("enter a number between 10 & 20: "))
wr = textwrap.TextWrapper()
wr.width = lLength
wr.expand_tabs = True
wraped = wr.wrap(file)
print("Here is your output formated to a max of", lLength, "characters per line: ")
print(wraped)
main()
When I do this instead of wrapping it prints everything in the file as a list with commas and brackets, instead of wrapping them.
textwrap.TextWrapper.wrap "returns a list of output lines, without final newlines."
You could either join them together with a linebreak
print('\n'.join(wrapped))
or iterate through and print them one at a time
for line in wrapped:
print(line)

Input and Output program for python

So I have a question that requires this The features : color,size,flesh and class are separated by spaces. Write a Python program that asks the user for the names of the input file (in this case animals.txt) and the output file (any name). The program reads in the lines of the input file, ignores comment lines (lines starting with #) and blank lines and computes and prints the answers to the following questions:
Total number of animals?
Total number of dangerous animals?
Number of large animals that are safe?
Number of animals that are brown and dangerous?
Number of safe animals with red color or hard flesh?
So I finished the program and everything seems to be working but so far when I enter the code and initiate the program, everything works, no errors, nothing but no output file gets generated. I don't know what is wrong exactly but if someone could point me in the right direction it would be highly appreciated.
import os.path
endofprogram = False
try:
filename1 = input("Enter the name of input file: ")
filename2 = input("Enter the name of output file: ")
while os.path.isfile(filename2):
filename2 = input("File Exists! Enter new name for output file: ")
infile = open(filename1, 'r')
ofile = open(filename2, "w")
except IOError:
print("Error reading file! Program ends here")
endofprogram = True
if (endofprogram == False):
alist = []
blist = []
clist = []
largesafe = 0
dangerous = 0
browndangerous = 0
redhard = 0
for line in infile:
line = line.strip("\n")
if (line != " ") and (line[0] != "#"):
colour, size, flesh, clas = line.split('\t')
alist = alist.append(colour)
animals = alist.count()
while clas == "dangerous":
dangerous = dangerous + 1
while size == "large" and clas == "safe":
largesafe = largesafe + 1
while colour == "brown" and clas == "dangerous":
browndangerous = browndangerous + 1
while colour == "red" and flesh == "hard":
redhard = redhard + 1
ofile.write(print("Animals = \n", animals))
ofile.write(print("Dangerous = \n", dangerous))
ofile.write(print("Brown and dangerous = \n", browndangerous))
ofile.write(print("Large and safe = \n", largesafe))
ofile.write(print("Safe and red color or hard flesh= \n", redhard))
infile.close()
ofile.close()
Your indentation has completely messed the program up. The biggest offender is this section:
except IOError:
print("Error reading file! Program ends here")
endofprogram = True
if (endofprogram == False):
The if line will only ever be executed right after the endofprogram = True line, at which point endofprogram == False will be false, and so nothing in the if block — which include the rest of the program — will be executed. You need to dedent everything from the if onwards by one level.
Maybe you can remove the print inside ofile.write
ofile.write(print("Animals = \n", animals))
to
ofile.write("Animals = \n" + str(animals))

A simple IF statement in python

I'm having trouble getting an "Else" statement to work.
My code looks like this so far:
roomNumber = (input("Enter the room number: "))
def find_details(id2find):
rb_text = open('roombookings2.txt', 'r')
for line in rb_text:
s = {}
(s['Date'], s['Room'], s['Course'], s['Stage']) = line.split(",")
if id2find == (s['Room']):
yield(s)
rb_text.close()
for room in find_details(roomNumber):
print("Date: " + room['Date'])
print("Room: " + room['Room'])
print("Course: " + room['Course'])
print("Stage: " + room['Stage'])
So when i do a positive search and get multiple matches in my text file, i get well organised results.
However, i'm trying to get it to tell me if invalid input data is entered and re-ask for the room number until the correct data is input.
I tried using an "Else" statement about the "Yield(s)" but it wont accept it.
Any ideas?
Python blocks are delineated by indentation so the "else:" (note lowercase and with a colon to indicate the start of a block) should be at the same indent level as the if statement.
def find_details(id2find):
rb_text = open('roombookings2.txt', 'r')
for line in rb_text:
s = {}
(s['Date'], s['Room'], s['Course'], s['Stage']) = line.split(",")
if id2find == (s['Room']):
yield(s)
else:
print "this print will execute if d2find != (s['Room'])"
# ... also see DrTyrsa's comment on you question.
But I suspect you don't really want to use an else clause anyway, where would you go from there? This looks an awful lot like an assignment so I'm not going to post an exact solution.
You can do it like this:
def find_details(id2find):
found = False
with open('roombookings2.txt', 'r') as rb_text:
for line in rb_text:
s = {}
(s['Date'], s['Room'], s['Course'], s['Stage']) = line.split(",")
if id2find == s['Room']:
found = True
yield(s)
if not found:
raise ValueError("No such room number!")
while True:
roomNumber = (input("Enter the room number: "))
try:
for room in find_details(roomNumber):
print("Date: " + room['Date'])
print("Room: " + room['Room'])
print("Course: " + room['Course'])
print("Stage: " + room['Stage'])
break
except ValueError as e:
print str(e)

Categories