How to remove \n at end of file name - python-3.x

When the following bit of code runs, most specifically the last 'else'condition, I get this error: OSError: [Errno 22] Invalid argument: 'My Name\n-Groups.txt'
What should I do so that '\n' isn't included in the file name as I would like it to just be 'My Name-Groups.txt'.
def add_child_to_group():
file = open("Children.txt", 'r') # open the Children.txt file
lineList = file.readlines()
lineList.sort()
file.close()
choice1 = choicebox('Choose a child to enter into a group.', 'Add child to a group. ', choices=lineList)
if choice1 is None:
print("You cancelled... returning to the main menu.")
main()
return
else:
file = open("Groups.txt", 'r')
lineList = [line.strip() for line in file]
choice2 = choicebox("Which group would you like to add the child to?", "Choose a group.",
choices=lineList)
file.close()
if choice2 is None:
print("You cancelled... returning to the main menu.")
main()
return
else:
if choice1 in open('%s.txt' % choice2).read():
child_already_in_group(choice1, choice2)
return
else:
file1 = open('%s.txt' % choice2, 'a')
file1.write(str(choice1))
print(str(choice1) + "was added to the " + str(choice2) + " group")
file1.close()
file2 = open('%s-Groups.txt' % choice1, 'a')
file2.write(str(choice2))

Something like this can do:
>>> st = 'My Name\n-Groups.txt'
>>> st.replace('\n','')
'My Name-Groups.txt'
>>>
So, in your code, you can make the following change:
file2 = open(('%s-Groups.txt' % choice1).replace('\n',''), 'a')

Related

Simple Python File I/O spell check program

For a class I have to create a simple spell checking program that takes two files as inputs, one containing correctly spelled words and one containing a paragraph with a few misspelled words. I thought I had it figured out but I am getting an error I have never seen before. When the program finishes it gives the error:
<function check_words at 0x7f99ba6c60d0>
I have never seen this nor do I know what it means, any help in getting this program working would be appreciated. Program code is below:
import os
def main():
while True:
dpath = input("Please enter the path to your dictionary:")
fpath = input("Please enter the path to the file to spell check:")
d = os.path.isfile(dpath)
f = os.path.isfile(fpath)
if d == True and f == True:
check_words(dpath, fpath)
break
print("The following words were misspelled:")
print(check_words)
def linecheck(word, dlist):
if word in dlist:
return None
else:
return word
def check_words(dictionary, file_to_check):
d = dictionary
f = file_to_check
dlist = {}
wrong = []
with open(d, 'r') as c:
for line in c:
(key) = line.strip()
dlist[key] = ''
with open(f, 'r') as i:
for line in i:
line = line.strip()
fun = linecheck(line, dlist)
if fun is not None:
wrong.append(fun)
return wrong
if __name__ == '__main__':
main()
It's not an error, it's doing exactly what you are telling it to.
This line:
print(check_words)
You are telling it to print a function. The output you are seeing is just Python printing the name of the function and it's address: "printing the function".
Yes, don't do print(check_words), do print(check_words())
Furthermore, change check_words(dpath, fpath) to misspelled_words = check_words(dpath, fpath)
And change print(check_words) to print(misspelled_words)
Final code (with a few modifications):
import os
def main():
while True:
dpath = input("Please enter the path to your dictionary: ")
fpath = input("Please enter the path to the file to spell check: ")
d = os.path.isfile(dpath)
f = os.path.isfile(fpath)
if d == True and f == True:
misspelled_words = check_words(dpath, fpath)
break
print("\nThe following words were misspelled:\n----------")
#print(misspelled_words) #comment out this line if you are using the code below
#optional, if you want a better looking output
for word in misspelled_words: # erase these lines if you don't want to use them
print(word) # erase these lines if you don't want to use them
#------------------------
def linecheck(word, dlist):
if word in dlist:
return None
else:
return word
def check_words(dictionary, file_to_check):
d = dictionary
f = file_to_check
dlist = {}
wrong = []
with open(d, 'r') as c:
for line in c:
(key) = line.strip()
dlist[key] = ''
with open(f, 'r') as i:
for line in i:
line = line.strip()
fun = linecheck(line, dlist)
if fun is not None:
wrong.append(fun)
return wrong
if __name__ == '__main__':
main()

How to past Check 50 for Bleep.py in Pset 6?

The number of "*" printed fluctuates according to the length of string entered
def main():
# check command line argument
if len(argv) != 2:
print("Usage: python bleep.py dictionary")
exit(1)
else:
ban = set()
# Load txt file
with open(argv[1], "r") as f:
for line in f:
# strip the space and add to set
ban.add(line.strip())
# prompt user input
input = get_string("What message would you like to censor?\n")
# Split input into word tokens
token = input.split()
censored_msg = ""
for i in token:
if i.lower() in ban:
censored_msg = (censored_msg + "*"*(len(token)+1) + " ")
else:
censored_msg += i + " "
# print censored message
print(censored_msg.strip())
if __name__ == "__main__":
main()
It prints fine for some cases, such as
Input: heck my gosh
Output: **** my ****
But not so in others (should be **** ****)
Input: heck gosh
Output: * * (just 6 * for 8 letters)
Is it a typo? Check this line very carefully
censored_msg = (censored_msg + "*"*(len(token)+1) + " ")
and remember which is what here for i in token:

A permanent list change(Save python file)

I am a noob in python and i need help.I have made a phonebook where you can add the contacts.But the problem is that when i exit the program the changes to the list are not saved.I want the user to be able to make permanent changes to the list.I have seen posts about a file=open("something",'w') code to do this(I think) but i dont know where to insert this code and i dont really understand what it is.Could someone help me understand what this is about..Here is the full code:
name = ["ranga","hari"]
number = [9895497777,9]
book = {name[0]:number[0],name[1]:number[1]}
def search():
print("Contacts:")
for x in book:
print(x,':',book[x])
while 1:
count = 0
a = 0
ch1 = input("search: ")
try:
ch1 = int(ch1)
except ValueError:
while a < len(name):
result = name[a].find(ch1)
if result == -1:
a = a + 1
else:
print(name[a],number[a])
a = a + 1
count = count + 1
if count == 0:
print("Not available.Try again")
continue
else:
break
ch1 = str(ch1)
while a < len(number):
sumber = str(number[a])
result = sumber.find(ch1)
if result == -1:
a = a + 1
else:
print(name[a],number[a])
a = a + 1
count += 1
if count == 0:
print("Not available.try again")
continue
else:
break
def add():
print("What is the name of the contact you want to add?")
name1 = input()
name.append(name1)
while 1:
print("What is the number of this contact?")
number1 = input()
try:
number1 = int(number1)
except ValueError:
print("Please type a number..")
continue
number.append(number1)
book[name1] = number1
break
def remoe():
print("Reference:")
for x in book:
print(x,':',book[x])
while 1:
print("What is the name of the contact you want to remove?")
name2 = input()
if name2 in book:
increment = name.index(name2)
name.pop(increment)
number.pop(increment)
del book[name2]
break
else:
print("Not available.Please try again")
while 1:
print("Contacts:")
for x in book:
print(x, ':', book[x])
print("\nWhat do you want to do?\n1.Search for a person\n2.edit the phone book\n3.exit")
choice = input()
try:
choice = int(choice)
except ValueError:
print("Type 1,2 or 3")
continue
if choice == 1:
search()
elif choice == 2:
while 1:
print("Do you want to:\n1.Add a contact\n2.Remove a contact\n3.Go back to main menu")
ch2 = input()
if ch2 in['3']:
break
else:
try:
ch2 = int(ch2)
except ValueError:
print("Type 1 or 2..")
if ch2 == 1:
add()
elif ch2 == 2:
remoe()
elif choice == 3:
exit()
else:
print("Type 1,2 or 3")
I appreciate the help.
When you choose to add a contact, it does properly add the name and number to the list. But, that is it.
When you re-run the program, the list gets re-assigned due to the first 2 lines of your code:
name = ["ranga","hari"]
number = [9895497777,9]
So, you won't see the last changes.
This is where you should maintain a file which lives outside the scope of your code, rather than a list.
You can modify your add function like this:
def add():
print("What is the name of the contact you want to add?")
name1 = input()
#name.append(name1)
# Just add the name1 variable's value to the file
with open('contacts_list.txt', 'a+') as f:
f.write(name1 + '\n')
while 1:
print("What is the number of this contact?")
number1 = input()
try:
number1 = int(number1)
except ValueError:
print("Please type a number..")
continue
#number.append(number1)
# Similarly, append the number1 variable's value to file again.
with open('contacts_list.txt', 'w+') as f:
f.write(number1)
#book[name1] = number1
with open('contacts_list.txt', 'r') as f:
print(f.read())
break
Note: You would also need to change the other functions search and remove to read and write from the file. I've just given you a taste of how things are done. You need to modify your code and make it work.
Let me know if it helps.
I took your advice and made a new text file but i still did not know how to do it but after reading ur answers i understood and at last i came to this..
removelist = []
def search():
while 1:
search = str(input("Search: "))
if search not in["exit", "Exit"]:
with open('output.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()
def add():
print("Type the name of the contact:")
name = input()
while 1:
print("Type the number of this contact:")
number = input()
try:
number = int(number)
except ValueError:
print("Please type a number")
continue
number = str(number)
with open('output.txt', 'a+') as f:
f.write('\n' + name +' ' + number)
break
def remoe(): #this is where the problem comes in
while 1:
remove = str(input("Remove: "))
with open('output.txt', 'r+') as f:
line = f.readline()
while line:
if not remove in["Remove", "remove"]:
removelist.clear()
data = line.find(remove)
if not data == -1:
removelist.append(line) #This saves all the lines coming from the search to a
print(removelist) #removelist which can be accessed when you type in remove
line = f.readline() #But the problem is that if there is a \n at the end of the
else: #string then the remove function does not work
line = f.readline()
else:
print(removelist)
with open('output.txt', 'r') as f:
d = f.readlines()
f.close()
with open('output.txt', 'w') as f:
for i in d:
if i not in removelist:
f.write(i)
f.truncate()
f.close()
break
while 1:
with open('output.txt', 'r') as f:
data = f.read()
print("Contacts:")
print(data)
print('''What do you want to do?
1.Search for a contact
2.Edit contacts
3.Exit''')
f.close()
choice = input()
if choice in["1"]:
search()
elif choice in["2"]:
while 1:
print('''What do you wanna do:
1.Add a contact
2.Remove a contact
3.Exit to main menu''')
ch1 = input()
if ch1 in["1"]:
add()
elif ch1 in["2"]:
remoe()
elif ch1 in["3"]:
break
else:
print("Please type 1,2 or 3")
elif choice in[3]:
print("Ok bye")
else:
print("Please type 1,2 or 3")
Now the problem seems to be the remove function..if i try to remove a line with \n at the end of it then it wont work while the opp. seems to work.Any guess what i am doing here?
And thanks for the help Mayank porwal
At the first you should know name = ["ranga","hari"], number = [9895497777,9] that you have defined are in the code and you can not change those value, and after exit() they will reset to default value.
you should use of file (for example .txt file) in this issue:
1. you must create a .txt file in your project (for example Contacts.txt)
2. and write your information in there (for example in first line: Kourosh +98938....)
3. at the first step in your program you must read Contact.txt and load it in a structure like a list or dictionary (for example
>>> with open('workfile') as f:
... read_data = f.read()
>>> f.closed
)
4.now you can edit, add, remove structure.
5.and finally you can write structure in the file, before exit()
for example:
>>> with open('workfile') as f:
... f.write(s)
>>> f.closed

Write input to file, excluding final line

My simple assignment is to write a function that asks for a filename, and then repeatedly reads lines from the user and saves these lines to the named file.
It stops saving the lines when the user input is a single dot on a line by itself. The line containing the single dot is NOT saved.
Example output would look like:
Save to what file: mytest.txt
> This is
> my attempt at
> the problem.
>
> The last line was empty
> .
Saving file mytest.txt
5 lines saved
Here's my attempt:
def savefile():
filename = input("Save to what file: ")
infile = open(filename, "w")
line = ""
lineCount = 0
while line != ".":
line = input("> ")
infile.write(line + "\n")
lineCount += 1
print("Saving file", filename)
print(lineCount, "lines saved")
infile.close()
which works fine, except my while loop also saves the last line (the "." by itself on a line). I've also tried an if-else loop:
if line != ".":
line = input("> ")
infile.write(line + "\n")
lineCount += 1
else:
infile.close()
but this just saves the first line entered.
How can I exclude the last line entered?
Doesn't even need an explanation:
with open("my_file.txt","w") as file:
while True:
line = input("> ")
if line.strip() == ".":
break
else:
file.write(line + "\n")
You could try this by simply interchanging some of the lines in your code as follows:
def savefile():
filename = input("Save to what file: ")
infile = open(filename, "w")
line = input("> ")
lineCount = 0
while line != ".":
infile.write(line + "\n")
lineCount += 1
line = input("> ")
print("Saving file", filename)
print(lineCount, "lines saved")
infile.close()
It is just a little out of order, classic problem, move the input to above the while loop, I hope see why...
def savefile():
filename = input("Save to what file: ")
infile = open(filename, "w")
line = ""
lineCount = 0
# first lets get the line of input
line = input("> ")
# if the line is "." then don't do the following code.
while line != ".":
# if the line was not "." then we do this...
infile.write(line + "\n")
lineCount += 1
# get the input again, and loop, remember if we get "."
# we will break from this loop.
line = input("> ")
print("Saving file", filename)
print(lineCount, "lines saved")
infile.close()

Python: Checking Characters in String

So I keep trying to make this work but I do not know where it is going wrong. The text file contains:
III
###
This is what I have so far. I do not see what is wrong.
CHARACTERS = ["I","#"]
def checkFile():
inFile = open("random.txt","r")
text = inFile.read()
inFile.close()
x = True
for line in text:
line.strip()
for i in range(len(line)):
if line[i] in CHARACTERS:
x = True
else:
x = False
return False
return True
def main():
check = checkFile()
if check == False:
sys.exit()
elif check == True:
print("bye")
sys.exit()
main()
It should print "bye" because all the characters in the file are in the list; however it just exits without the print statement.
When a txt file contains two lines of text, one on top of each other, it also includes a hidden '\n'. To change that add '\n' to CHARACTERS, or copy the following code:
CHARACTERS = ["I","#", "\n"]
def checkFile():
inFile = open("random.txt","r")
text = inFile.read()
inFile.close()
x = True
for line in text:
line.strip()
for i in range(len(line)):
if line[i] in CHARACTERS:
x = True
else:
x = False
return False
return True
def main():
check = checkFile()
if check == False:
sys.exit()
elif check == True:
print("bye")
sys.exit()
main()
EDIT: I created a txt file called test.txt and I pasted your text into it. I then ran the following code:
>>> file = open('test.txt', 'r').read()
>>> file
'III\n\n###\n'
>>>
Because there are two lines in between, it has teo '\n's. You can get rid of this by either adding '\n' to CHARACTERS, or by calling text = inFile.read().split() with the split()
When you call line.strip(), you are not assigning line.strip() to any value. Thus, the '\n' remains 'unstripped', so to speak. Instead, call line = line.strip().

Resources