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.
Related
def add():
while True:
try:
a = int(input("How many words do you want to add:"))
if a >= 0:
break
else:
raise ValueError
except ValueError:
print("Not valid ")
return a
for i in range(add()):
key_i = input(f"Turkish meaning: {i + 1}: ")
value_i = input("translated version: ")
with open('words.txt', 'a+') as f:
f.write("'"+key_i+':')+ f.write(value_i+"'"+",")
My goal is to create my own dictionary,but I am adding a list into the txt file, so it is added into the txt file like this
words = {'araba:kol',
but when I search the txt file it gives me the whole list
def search():
while 1:
search = str(input("Search: "))
if search not in["exit", "Exit"]:
with open('words.txt', 'r+') as f:
line = f.readline()
while line:
data = line.find(search)
if not data == -1:
print(line.rstrip('\n'))
line = f.readline()
else:
line = f.readline()
else:
break
f.close()
What can I do to make it output like this
car:araba
Use JSON module to avoid having to write the dictionary line by line yourself.
import json
with open('words.json', 'a+') as f:
json.dump({key_i: value_i}, f)
with open('data.json', 'r') as f:
d2 = json.load(f)
d2 is now the data that you wrote to the file.
Note, that you should change the a+ to 'w' as you only have one dictionary per file.
I have tried to create a really simple program that counts the words that you have written. When I run my code, I do not get any errors, the problem is that it always says: "the numbers of words are 0" when it is clearly not 0. I have tried to add this and see if it actually reads anything from the file: print(data) . It doesn't print anything ): so there must be a problem with the read part.
print("copy ur text down below")
words = input("")
f = open("data.txt", "w+")
z = open("data.txt", "r+")
info = f.write(words)
data = z.read()
res = len(data.split())
print("the numbers of words are " + str(res))
f.close()
Thx in advance
This is beacuse you haven't closed the file after writing to it. Use f.close() before using z.read()
Code:
print("copy ur text down below")
words = input("")
f = open("data.txt", "w+")
z = open("data.txt", "r+")
info = f.write(words)
f.close() # closing the file here after writing
data = z.read()
res = len(data.split())
print("the numbers of words are " + str(res))
f.close()
Output:
copy ur text down below
hello world
the numbers of words are 2
After writing to f with f.write, you should close f with f.close before calling z.read. See here.
I used this code to delete a word from a text file.
f = open('./test.txt','r')
a = ['word1','word2','word3']
lst = []
for line in f:
for word in a:
if word in line:
line = line.replace(word,'')
lst.append(line)
f.close()
f = open('./test.txt','w')
for line in lst:
f.write(line)
f.close()
But for some reason if the words have the same characters, all those characters get deleted. So for e.g
in my code:
def cancel():
global refID
f1=open("refID.txt","r")
line=f1.readline()
flag = 0
while flag==0:
refID=input("Enter the reference ID or type 'q' to quit: ")
for i in line.split(','):
if refID == i:
flag=1
if flag ==1:
print("reference ID found")
cancelsub()
elif (len(refID))<1:
print("Reference ID not found, please re-enter your reference ID\n")
cancel()
elif refID=="q":
flag=1
else:
print("reference ID not found\n")
menu()
def cancelsub():
global refIDarr, index
refIDarr=[]
index=0
f = open('flightbooking.csv')
csv_f = csv.reader(f)
for row in csv_f:
refIDarr.append(row[1])
for i in range (len(refIDarr)):
if refID==refIDarr[i]:
index=i
print(index)
while True:
proceed=input("You are about to cancel your flight booking, are you sure you would like to proceed? y/n?: ")
while proceed>"y" or proceed<"n" or (proceed>"n" and proceed<"y") :
proceed=input("Invalid entry. \nPlease enter y or n: ")
if proceed=="y":
Continue()
break
elif proceed=="n":
main_menu
break
exit
break
def Continue():
lines = list()
with open('flightbooking.csv', 'r') as readFile:
reader = csv.reader(readFile)
for row in reader:
lines.append(row)
for field in row:
if field ==refID:
lines.remove(row)
break
with open('flightbooking.csv', 'w') as writeFile:
writer = csv.writer(writeFile)
writer.writerows(lines)
f = open('refID.txt','r')
a=refIDarr[index]
print(a)
lst = []
for line in f:
for word in a:
if word in line:
line = line.replace(word,'')
lst.append(line)
print(lst)
f.close()
f = open('refID.txt','w')
for line in lst:
f.write(line)
f.close()
print("Booking successfully cancelled")
menu()
When the code is run, the refID variable has one word stored in it, and it should replace just that word with a blank space, but it takes that word for e.g 'AB123', finds all other words which might have an 'A' or a 'B' or the numbers, and replace all of them. How do I make it so it only deletes the word?
Text file before running code:
AD123,AB123
Expected Output in the text file:
AD123,
Output in text file:
D,
Edit: I have added the entire code, and maybe you can help now after seeing that the array is being appended to and then being used to delete from a text file.
here's my opinion.
refIDarr = ["AB123"]
a = refIDarr[0] => a = "AB123"
strings in python are iterable, so when you do for word in a, you're getting 5 loops where each word is actually a letter.
Something like the following is being executed.
if "A" in line:
line = line.replace("A","")
if "B" in line:
line = line.replace("B","")
if "1" in line:
line = line.replace("1","")
if "2" in line:
line = line.replace("2","")
if "3" in line:
line = line.replace("3","")
they correct way to do this is loop over refIDarr
for word in refIDarr:
line = line.replace(word,'')
NOTE: You don't need the if statement, since if the word is not in the line it will return the same line as it was.
"abc".replace("bananan", "") => "abc"
Here's a working example:
refIDarr = ["hello", "world", "lol"]
with open('mytext.txt', "r") as f:
data = f.readlines()
for word in refIDarr:
data = [line.replace(word, "") for line in data]
with open("mytext.txt", "w") as newf:
newf.writelines(data)
The problem is here:
a=refIDarr[index]
If refIDarr is a list of words, accessing specific index makes a be a word. Later, when you iterate over a (for word in a:), word becomes a letter and not a word as you expect, which causes eventually replacing characters of word instead the word itself in your file.
To avoid that, remove a=refIDarr[index] and change your loop to be:
for line in f:
for word in refIDarr:
if word in line:
line = line.replace(word,'')
Every time I write a code I keep getting error. here is the code I have
def main():
outflow = open("studentList.txt", "r")
for line in outflile:
line[:-1].split(" ")
print(line)
main()
If your studentList file contain the name of the student one per each line so the way of reading is:
def main():
noOfStudents = 0
outflow = open("studentList.txt", "r")
for line in outflow:
noOfStudents+=1
print(line.rstrip("\n"))
print("Total no of students is :", noOfStudents)
outflow.close()
main()
Output:
student A
student B
student C
Total no of students is : 3
If students names are in line by line in the text file then use this
filename = "studentList.txt"
with open(filename) as f:
lines = f.read().splitlines()
print(lines)
or if students names are separated from space then use the following one
filename = "studentList.txt"
with open(filename, 'r') as f:
lines = f.read().encode("utf-8").replace(" ", "\n")
print(lines)
you do not have any outflile (probably a typo) difined this will raise NameError, so you can use:
def main():
outflow = open("studentList.txt", "r")
for line in outflow:
line[:-1].split(" ")
print(line)
main()
even better:
with open("studentList.txt", "r") as outflow:
for line in outflow:
line = line.rstrip().split(" ")
print(line)
Why does this create the file but not write the code into it?
import os
#List for text
mainlist = []
#Definitions
def main():
print("Please Input Data(Type 'Done' When Complete):")
x = input()
if x.lower() == 'done':
sort(mainlist)
else:
mainlist.append(x)
main()
def sort(mainlist):
mainlist = sorted(mainlist, key=str.lower)
for s in mainlist:
finalstring = '\n'.join(str(mainlist) for mainlist in mainlist)
print(finalstring)
print("What would you like to name the file?:")
filename = input()
with open(filename + ".txt", "w") as f:
f.write(str(finalstring))
print("\nPress Enter To Terminate.")
c = input()
main()
#Clears to prevent spam.
os.system("cls")
The file is made, and the data is stored... But finalstring's content isn't written into it. The file remains blank.
You're calling sort(mainlist) multiple times and the file is being overwritten each time. Change the open mode to a like:
with open(filename + ".txt", "a") as f:
f.write(str(finalstring))
See http://docs.python.org/3.2/tutorial/inputoutput.html#reading-and-writing-files