So I tried to run the code trying to print the lines starting with "How" taking the file name from the user, but the output shows there are 0 lines starting with "How".
content in the file, read.txt-
Hey there, this is Sohail Hassan.
How are you?
How is everything going?
How is everything at college?
fhand = input("enter the file name")
try:
fname = open(fhand)
except:
print("can't open the file")
count = 0
for line in fhand:
if line.startswith("How"):
count = count+1
print("There are,",count,"lines in this file.")
Full corrected version of your code, with a few improvements:
fname = input("enter the file name")
try:
with open(fname, 'w') as fhand:
for line in fhand:
if line.startswith("How"):
count += 1
except:
print("can't open the file '" + fname + "'")
print("There are " + count + " lines starting with 'How' in this file.")
Related
Been trying to write my PYTHON code but it will always output the file with a blank line at the end. Is there a way to mod my code so it doesn't print out the last blank line.
def write_concordance(self, filename):
""" Write the concordance entries to the output file(filename)
See sample output files for format."""
try:
file_out = open(filename, "w")
except FileNotFoundError:
raise FileNotFoundError("File Not Found")
word_lst = self.concordance_table.get_all_keys() #gets a list of all the words
word_lst.sort() #orders it
for i in word_lst:
ln_num = self.concordance_table.get_value(i) #line number list
ln_str = "" #string that will be written to file
for c in ln_num:
ln_str += " " + str(c) #loads line numbers as a string
file_out.write(i + ":" + ln_str + "\n")
file_out.close()
Output_file
Line 13 in this picture is what I need gone
Put in a check so that the new line is not added for the last element of the list:
def write_concordance(self, filename):
""" Write the concordance entries to the output file(filename)
See sample output files for format."""
try:
file_out = open(filename, "w")
except FileNotFoundError:
raise FileNotFoundError("File Not Found")
word_lst = self.concordance_table.get_all_keys() #gets a list of all the words
word_lst.sort() #orders it
for i in word_lst:
ln_num = self.concordance_table.get_value(i) #line number list
ln_str = "" #string that will be written to file
for c in ln_num:
ln_str += " " + str(c) #loads line numbers as a string
file_out.write(i + ":" + ln_str)
if i != word_lst[-1]:
file_out.write("\n")
file_out.close()
The issue is here:
file_out.write(i + ":" + ln_str + "\n")
The \n adds a new line.
The way to fix this is to rewrite it slightly:
ln_strs = []
for i in word_lst:
ln_num = self.concordance_table.get_value(i) #line number list
ln_str = " ".join(ln_num) #string that will be written to file
ln_strs.append(f"{i} : {ln_str}")
file_out.write('\n'.join(ln_strs))
Just btw, you should actually not use file_out = open() and file_out.close() but with open() as file_out:, this way you always close the file and an exception won't leave the file hanging
I'm trying to write a program that assigns prices to a list, but I'm having trouble. I keep getting a NameError, that costlist is not defined. The program should ask for an input, append it to the list, and go through the whole list, then write it to the .txt file.
import os
def main():
if os.path.exists("costlist.txt"):
os.remove("costlist.txt")
print ("Assignment 6")
print ()
filename = input("Enter a file name, please. Or enter end to end.")
while filename != "end":
try:
file = open(filename, "r")
listie = file.readlines()
for item in listie:
print(item)
break
except FileNotFoundError:
filename = input("Sorry, that file wasn't found. Try again?")
if filename == "end":
exit
file.close()
listie.sort()
file = open(filename, "w")
for item in listie:
file.write(item.strip("\n"))
file.close()
for item in listie:
cost = input(print( item + "should cost how much?"))
try:
float.cost
except ValueError:
print ("You entered an invalid float that can't convert string to float:" + cost)
print ("Skipping to the next item after" + item)
print (item + "has a cost of" + cost + "dollars")
file = open(costlist.txt, "a")
file.append(cost)
print ("Cost List")
file = open (costlist.txt, "r")
for item in file:
print (item)
print ("Program End")
You forgot to enclose the file name by quotes.
Change file = open(costlist.txt, "a") to file = open("costlist.txt", "a")
And
file = open (costlist.txt, "r") to file = open ("costlist.txt", "r")
In this spellchecking program i created i seem to be getting a error when trying to write to the output file.The file is created but instead of the output being written an error " <_io.TextIOWrapper name='f.txt' mode='w' encoding='cp1252'>name " is.
I've tried looking for solutions.
print('Spell checking program for Exam 3 lab')
inputFile = input('Enter the name of the file to input from: ')
outputFile = input('Enter the name of the file to output to: ')
f = open("linuxwords.txt", "r")
sent = open(inputFile+ '.txt', "r")
butt = open(outputFile+'.txt', 'w')
word = sent.readline()
print ("mispelled words are:")
while word:
word = word.lower()
success = False
x = word.split()
y=len(x)
for i in x:
success = False
f = open("linuxwords.txt", "r")
line = f.readline()
while line:
if i == line.strip():
success = True
break
line = f.readline()
f.close()
if success == False:
print (i)
word = sent.readline()
with open(outputFile+'.txt', 'w') as f:
f.write(str(butt))
f.write(i)
try:
'''''''
I'm sure my mistake is here, idk
'''''''
f = open(outputFile, "w")
f.write(i)
except:
print('The file',outputFile, 'did not open.')
sent.close()
''''''
Result below
''''''''
Spell checking program for Exam 3 lab
Enter the name of the file to input from: spw
Enter the name of the file to output to: f
misspelled words are:
deks
chris
delatorre
huis
lst
f = open(outputFile)
f.write(i)
You're opening the file for reading, and then trying to write to it.
def main():
read()
def read():
fileName=input("Enter the file you want to count: ")
infile=open(fileName , "r")
text=infile.readline()
count=0
while text != "":
text=str(count)
count+=1
text=infile.readline()
print(str(count)+ ": " + text)
infile.close()
main()
-the referenced .txt file has only two elements
44
33
-the output of this code should look like
1: 44
2: 33
-my output is
1: 33
2:
im not sure why the program is not picking up the first line in the referenced .txt file. The line numbers are correct however 33 should be second to 44.
The reason is explained in the comments:
def main():
read()
def read():
fileName=input("Enter the file you want to count: ")
infile=open(fileName , "r")
text=infile.readline() ##Reading the first line here but not printing
count=0
while text != "":
text=str(count)
count+=1
text=infile.readline() ##Reading the 2nd line here
print(str(count)+ ": " + text) ##Printing the 2nd line here, missed the first
##line
infile.close()
main()
Modify the program as:
def main():
read()
def read():
fileName= input("Enter the file you want to count: ")
infile = open(fileName , "r")
text = infile.readline()
count = 1 # Set count to 1
while text != "":
print(str(count)+ ": " + str(text)) # Print 1st line here
count = count + 1 # Increment count to 2
text = infile.readline() # Read 2nd line
infile.close() # Close the file
main()
def main():
read()
def read():
fileName=input("Enter the file you want to count: ")
with open(fileName,'r') as f:
print('\n'.join([' : '.join([str(i+1),v.rstrip()]) for i,v in enumerate(f.readlines())]))
main()
I'm very confused by your read function. You start by reading the first line into text:
text=infile.readline()
Presumable at this point text contains 44.
You then immediately demolish this value before you've done anything with it by overwriting it with:
text = str(count)
ie you read two lines before printing anything at all.
You should print the value of text before you overwrite it with the next readline.
Simply move the print statement before readline:
while text != "":
count+=1
print(str(count)+ ": " + text)
text=infile.readline()
My program is supposed to take a text file, print the contents, count the lines, ask for a string input, remove every occurrence of that string, say how many times the string was removed, and then output the new contents of the file. We were asked to use one file, not an input and an output file.
My code works and does everything it's supposed to up until I try to store the changes in the file at the end of the char_count function and the print_output function seems to not be working right at all.
If I have an input file of contents:
Apples
Oranges
Bananas
Apples
Oranges
Bananas
if I try to remove Bananas, the resulting file contents for the input file is:
ApplesOrangesApplesOrangesles
Oranges
Bananas
I've been trying to figure out what's going on with no progress, and our course textbook doesn't seem to mention overwriting input files, but we're required to do it for an assignment. What is wrong with my last two functions?
def main():
input_file_name = input("Please Enter the name of your text file: ")
infile = open(input_file_name, "r+")
print()
print("---------------------------------------")
print("THE FILE CONTENTS ARE")
print("---------------------------------------")
print_file(infile)
print("---------------------------------------")
count_lines(infile)
print("---------------------------------------")
input_string = input("Please enter the word or string of words you want to remove from the text file: ")
print("---------------------------------------")
char_count(infile, input_string)
print("---------------------------------------")
print("THE NEW FILE CONTENTS ARE")
print_output(infile)
print("---------------------------------------")
infile.close()
def print_file(infile):
infile.seek(0)
allLines = infile.readlines()
for line in allLines:
text = line.rstrip()
print(text)
def count_lines(infile):
infile.seek(0)
allLines = infile.readlines()
count = 0
char = " "
for line in allLines :
text = line.rstrip()
while char != "":
char = infile.read(1)
count = count + 1
print("THE NUMBER OF LINES IS: %d " % count)
def char_count(infile, input_string) :
count = 0
infile.seek(0)
allLines = infile.readlines()
infile.seek(0)
for line in allLines:
while input_string in line:
line = line.replace(input_string, "")
count = count + 1
text = line.rstrip()
infile.write(text)
print("NUMBER OF OCCURRENCES REMOVED IS: %d" % count)
def print_output(infile):
infile.seek(0)
allLines = infile.readlines()
for line in allLines:
text = line.rstrip()
print(text)
main()
you have to truncate the file first to get the required output.
def main():
input_file_name = input("Please Enter the name of your text file: ")
infile = open(input_file_name, "r+")
print()
print("---------------------------------------")
print("THE FILE CONTENTS ARE")
print("---------------------------------------")
print_file(infile)
print("---------------------------------------")
count_lines(infile)
print("---------------------------------------")
input_string = input("Please enter the word or string of words you want to remove from the text file: ")
print("---------------------------------------")
char_count(infile, input_string)
print("---------------------------------------")
print("THE NEW FILE CONTENTS ARE")
print_output(infile)
print("---------------------------------------")
infile.close()
def print_file(infile):
infile.seek(0)
allLines = infile.readlines()
for line in allLines:
text = line.rstrip()
print(text)
def count_lines(infile):
infile.seek(0)
allLines = infile.readlines()
count = 0
char = " "
for line in allLines :
text = line.rstrip()
while char != "":
char = infile.read(1)
count = count + 1
print("THE NUMBER OF LINES IS: %d " % count)
def char_count(infile, input_string) :
count = 0
infile.seek(0)
allLines = infile.readlines()
infile.seek(0)
infile.truncate() #Empty your file first to rewrite it
for line in allLines:
while input_string in line:
line = line.replace(input_string, "")
count = count + 1
text = line.rstrip()
if(text != ""):
infile.write(text + "\n") #To write in multiple lines
print("NUMBER OF OCCURRENCES REMOVED IS: %d" % count)
def print_output(infile):
infile.seek(0)
allLines = infile.readlines()
for line in allLines:
text = line.rstrip()
print(text)
main()