The following code executes properly in IDLE but return an error in console.
import sys, math, string, time, os
from time import *
restart0 = True
while restart0:
def addDecimal():
print(".", end="\r")
breakout0 = False
invalidcommand0 = True
while invalidcommand0:
file = open("HighScores.txt","r+")
sleep(0.5)
print("\nWelcome to VACSecureServers™\n")
start = input("Would you like to start the program? ")
if start.lower() == "yes":
print("\n1. Display high scores\n2. Add a new high score\n3. Clear all high scores\n4. Quit")
option = input()
if option == "1":
print (file.read())
if os.stat("highscores.txt").st_size==0:
print("There are no highscores currently in the system, please return and input some.")
elif option == "2":
numberAppend = int(input("How many scores would you likes to add to the program? "))
for loop in range(numberAppend):
name = input("Enter the name of the user:" )
score = input("Enter a score: ")
file.write(name+","+score+","+strftime("%d/%m/%y %H:%M:%S\n"))
elif option == "3":
open("HighScores.txt", 'w').close()
print("Highscores resetting")
sleep(0.4)
addDecimal()
sleep(0.6)
addDecimal()
sleep(0.9)
addDecimal()
sleep(1.2)
print("Successfully reset!")
sleep(2)
elif option == "4":
sys.exit()
file.close()
This is the error I get:
Traceback (most recent call last):
File "E:\script.py", line 12, in <module>
print("\nWelcome to VACSecureServers™\n")
File: "C:\Python3\lib\encodings\cp437.py", line 19, in encode
return codecs.charmap_encode(input,self.errors,encoding_map)[0]
UnicodeEncodeError: 'charmap' codec can't encode character '\u2122' in position 29: character maps to <undefined>
What could be the problem?
It is because of this line
print("\nWelcome to VACSecureServers™\n")
You have a ™ symbol in it. Your console probably can't display it, but IDLE supports unicode characters. Remove it and your code should work just fine.
Related
I'm still a newb to this, so sorry if I mess up :D
So I'm trying to write a script that goes through some .xml files to get certain lines and put's them into an excel sheet.
Code:
import os
import openpyxl
def main():
print_header()
folder = get_folder_from_user()
if not folder:
print("Sorry, that folder doesn't exist.")
return
text = get_search_text_from_user()
if not text:
print("Sorry, I can't search for nothing.")
return
count = input("Show match count? y/n")
name = "output.xlsx"
# name = input("Name for workbook: ")
x = []
output = search_file(folder, text)
match_count = 0
for i in output:
match_count += 1
string = i
string = string.split(">")
string = string[1]
string = string.split("<")
string = string[0]
i = string
print(i)
x.extend([i])
write_to_workbook(name, x)
if count == "y":
print("==================")
print("Found {} matches".format(match_count))
print("==================")
def write_to_workbook(name, x):
wb = openpyxl.Workbook()
ws = wb.active
a = 1
ws.append(x)
wb.save("C:/Users/Kevin/Desktop/{}".format(name))
a += 1
def print_header():
print("-----------------------------------")
print("----------File Search App----------")
print("-----------------------------------")
print()
def get_folder_from_user():
folder = input("Which folder do you want to search? ")
if not folder or not folder.strip():
return None
if not os.path.isdir(folder):
return None
return os.path.abspath(folder)
def get_search_text_from_user():
print("Which data do you want me to copy for you?")
print("[1]SeqTest Read")
print("[2]SeqTest Write")
print("[3]Random 4K1TTest Read")
print("[4]Random 4K1TTest Write")
print("[5]Random 4K64TTest Read")
print("[6]Random 4K64TTest Write")
print("[7]AccTimeTest Read")
print("[8]AccTimeTest Write")
print("[9]Score")
print("[0]All")
choice = int(input("Choose now: "))
if choice == 1:
line = 15
elif choice == 2:
line = 16
elif choice == 3:
line = 19
elif choice == 4:
line = 20
elif choice == 5:
line = 23
elif choice == 6:
line = 24
elif choice == 7:
line = 27
elif choice == 8:
line = 28
elif choice == 9:
line = 99
elif choice == 0:
line = 100
else:
line = 0
line = 15
return int(line)
def search_folders(folder, line):
items = os.listdir(folder)
for item in items:
full_item = os.path.join(folder, item)
if os.path.isdir(full_item):
yield from search_folders(full_item, line)
else:
yield from search_file(full_item, line)
def search_file(filename, line):
with open(filename, 'r', encoding='utf-8') as fin:
lines = fin.readlines()
if line == 99:
print(lines[31])
print(lines[32])
print(lines[33])
yield ("/n".join(lines[31:34]))
elif line == 100:
s = 0
while s < 10:
print(filename)
print(lines[4])
if line == 15 or 16:
print("Seq")
if line == 15:
print("Read")
else:
print("Write")
elif line == 19 or 20:
print("4k ")
if line == 19:
print("Read")
else:
print("Write")
elif line == 23 or 24:
print("4k 64")
if line == 23:
print("Read")
else:
print("Write")
elif line == 27 or 28:
print("Acc")
if line == 27:
print("Read")
else:
print("Write")
elif line == 99:
print("")
yield (lines[line])
else:
print(filename)
print(lines[4])
if line == 15 or 16:
print("Seq")
if line == 15:
print("Read")
else:
print("Write")
elif line == 19 or 20:
print("4k ")
if line == 19:
print("Read")
else:
print("Write")
elif line == 23 or 24:
print("4k 64")
if line == 23:
print("Read")
else:
print("Write")
elif line == 27 or 28:
print("Acc")
if line == 27:
print("Read")
else:
print("Write")
elif line == 99:
print("")
yield (lines[line])
if __name__ == '__main__':
main()
In short:
User has to type in the directory with the text files.
Then the wanted lines are chosen. (Fixed to line 15 for testing. I didn't get to the point to fix a problem when I want every line specified in the selection).
The user is then asked if he wants the total amount of matches.
Then it runs through all the text files and outputs line 15 of every file (just some data from ssd benchmarks).
The data is denn written into an excel file.
The code is working mostly. I still have to figure out how to properly output the data to excel (format is not as I want it).
But the problem is that the permissions to the directory change as soon as I add this Code:
def trigger_search(filename, line):
xyz = search_file(filename, line)
return xyz
As soon as I add this I get an errno 13: Permission denied.
It can't access the directory with the .xml files anymore.
Even if I delete the added code, I still get this error.
Only workaround is to copy the "unchanged" code (without the trigger_search) and overwrite the .py file.
Just copy paste and it works fine (no matter how often I run the code).
Any hint why this happens and how to fix this?
Please don't be too harsh because of the code, I know it's really newbie like. It'll be made properly as soon as it works :D
Nevermind guys.
I'm just dumb.
in the trigger_search I had to use search_folders, not search_file.
When changing the code back, I also replaced it with search_file although it was search_folders before in main method..
Using the right method actually works.
I'm so sorry...
The reason here that it is returning an error is because you have not run it as an administrator. Before I show you how to solve the problem, you will either need to be an administrator on your computer or you will have to know the password of an administrator. Also, this answer assumes that you are running Windows on your computer.
2 WAYS IF YOU RAN THIS PROGRAM FROM CMD
There are two ways to do this. The first way is to run the program "Run" (it was automatically installed by Windows), then type in cmd.exe. The second way is to tap the Windows key and look up cmd, and right-click the button that says "Command Prompt", and click on the button that says "Run as administrator".
The second way is to open the Command Prompt, and type in runas /profile /user:administrator “insert\path\here\program.py” where "administrator" should be replaced with your username on the computer, and "insert\path\here" should be replaced with the path where your program is in, and "program.py" should be replaced with the name of your program (if you are in the same directory as the program, then you do not need to include the path.)
1 WAY IF YOU RAN THIS PROGRAM FROM THE WINDOWS SEARCH BAR
When in the Windows Search Bar (at the bottom-left), then search up your program's filename (for example, "program.py") then right-click it and click the button that says "Run as adminstrator".
The reason for me asking the question here is that I did not find a solution elsewhere. I'm having the following error with my PyCharm 4.0.5 program while trying to run a Python script. It was working fine the one day and when I tried using it this afternoon I got the following error after tying to run a program which I am 100% has no errors in it.
In the message box I got the following error:
Failed to import the site module
Traceback (most recent call last):
File "C:\Python34\lib\site.py", line 562, in <module>
main()
File "C:\Python34\lib\site.py", line 544, in main
known_paths = removeduppaths()
File "C:\Python34\lib\site.py", line 125, in removeduppaths
dir, dircase = makepath(dir)
File "C:\Python34\lib\site.py", line 90, in makepath
dir = os.path.join(*paths)
AttributeError: 'module' object has no attribute 'path'
Process finished with exit code 1
I have never seen an error of this kind and don't know where to start tackling this problem.
Any feedback will be greatly appreciated!
The code looks like the following, and I seem to have forgotten to mention that it gives me the exact same error for every single .py script on my computer.
import turtle
wn = turtle.Screen()
alex = turtle.Turtle()
def hexagon(var):
for i in range(6):
alex.right(60)
alex.forward(var)
def square(var):
for i in range(4):
alex.forward(var)
alex.left(90)
def triangle(var):
for i in range(3):
alex.forward(var)
alex.left(120)
def reset():
alex.clear()
alex.reset()
x = True
while x:
alex.hideturtle()
choice = input("""
Enter the shape of choice:
a. Triangle
b. Square
c. Hexagon
""")
if choice.lower() == "a":
length = input("Enter the desired length of the sides: ")
triangle(int(length))
restart = input("Do you wish to try again? Y/N ")
if restart.lower() == "n":
x = False
else:
reset()
if choice.lower() == "b":
length = input("Enter the desired length of the sides: ")
square(int(length))
restart = input("Do you wish to try again? Y/N ")
if restart.lower() == "n":
x = False
else:
reset()
if choice.lower() == "c":
length = input("Enter the desired length of the sides: ")
hexagon(int(length))
restart = input("Do you wish to try again? Y/N ")
if restart.lower() == "n":
x = False
else:
reset()
print("Thank you for using your local turtle services!")
You must have a python file named os.py which is being imported instead of the "real" os module.
I am able to encode the message using the ASCII table but unfortunately I am unable to decode the message. After the user the gets the result he/she will type either yes or no to redo the message to the original input. Thanks!
def main():
message = input("Please input the message you want to encode: ")
for ch in message:
print(ord(ch))
print()
decode = input("Would you like to decode it? (Yes or No?): ")
if decode == str('yes', 'Yes'):
plainText = ""
for ch in message:
numCode = eval(decode)
plainText = plainText + chr(message)
print("Your decoded message is: ", plainText)
else:
print("Thank you for encrypting with us today!")
main()
You should store the encoded message after the user provides it and you encode it with ord:
message = input("Please input the message you want to encode: ")
encoded = "".join([ord(ch) for ch in message])
The next problematic line is this:
plainText = plainText + chr(message)
This tries to decode the entire message with chr on every iteration. It causes an error message:
>>> chr("abc")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: an integer is required
Instead of chr(message) it should be chr(ch), so it decodes each character separately. You can also do it more efficiently with "".join():
def main():
message = input("Please input the message you want to encode: ")
for ch in message:
print(ord(ch))
print()
decode = input("Would you like to decode it? (Yes or No?): ")
if decode == str('yes', 'Yes'):
plain_text = "".join([chr(ch) for ch in encoded])
print("Your decoded message is: ", plain_text)
else:
print("Thank you for encrypting with us today!")
main()
Also note that variable names should be snake case in Python
Running
I am running Python version 3.5, from the cmd prompt on Windows 7
What is in the .txt file and what the cmd outputs
What the cmd prompt outputs
What the .txt contains
My current code
"""Opens a file and let\'s you read it and write to it"""
open_pls = open("text.txt", "a+")
#Main function
def read_write():
program_running = True
while program_running == True:
choice = input("Write R for read, write W for write or write X for exit:")
choice = choice.upper()
if choice == "W":
what_write = input("What do you want to write to the end of the file?:")
open_pls.write(what_write)
print("Succesfully written!")
print("Running program again...")
continue
elif choice == "R":
print("This file contains:")
read_pls = open_pls.read()
print(read_pls)
print("Running program again...")
continue
elif choice == "X":
program_running = False
open_pls.close()
else:
print("That was not a valid command!")
print("Running program again...")
continue
run = input("Run the program? (Y/N):")
run = run.upper()
if run == "Y":
read_write()
elif run == "N":
input("Exit program? Press enter:")
else:
input("Exit program? Press enter:")
I think the problem lies somewhere in here
elif choice == "R":
print("This file contains:")
read_pls = open_pls.read()
print(read_pls)
print("Running program again...")
continue
When you open the file with the 'a' append mode, the OS gives you a file with the file position at the end of the file.
You could try to seek back to the start first, but it depends on your OS if that'll actually be permitted:
open_pls.seek(0)
read_pls = open_pls.read()
You may want to open the file in 'r+' mode instead, and seek to the end when writing.
When you open a file with 'a' mode, the file is seeks to the end. To get the contents of the file, you have to seek back to the beginning: open_pls.seek(0).
I need to make my program start over in Python if the enter key is pressed. I found this question and solution: how to check if the enter key is pressed python. However when I googled event.keysym, it seemed to have something to do with Tkinter which I don't think I have.
When I try using the solution I get an error:
Traceback (most recent call last):
File "/home/q/Desktop/PigsAndBulls.py", line 52, in <module>
if event.keysym == 'Return':
NameError: name 'event' is not defined
I am a complete newbie having just completed a course with Dr. Severance on Coursera.
Here is the program I wrote to play pigs and bulls at work. Everything works as I want. The only problem is to exit the program if any key other than the "enter" button is pushed.
while True:
while True:
word= raw_input("Enter a four letter English word with no repeating letters: ")
print
if len(word) <> 4:
print "What part of 'four letter word' did you not understand? Try again."
print
continue
else: break
guesses = 0
while True:
correct = 0
position = 0
cnt = 0
result = 0
guess= raw_input("Enter a guess: ")
guesses = guesses+1
#print "guessses", guesses
for w in guess:
cnt = cnt+1
#print "cnt", cnt
position=0
for g in word:
position=position+1
#print "position", position
if g == w:
correct = correct+1
if position == cnt:
result = result+1
#print "result", result
print
print "Number correct:", correct
print "Number in the right position:", result
print
if correct<>4 and result<>4:
print "Give me another guess"
print
continue
elif correct == 4 and result == 4:
print
print "YOU WIN"
print
print "It took you", guesses, " guesses to get it right"
print
break
answer= raw_input("press ""enter"" to play again")
if event.keysym == 'Return':
continue
else:
exit
print
print
Then I thought, maybe I have replace "event" with my string variable "answer" but then I got this error:
Traceback (most recent call last):
File "/home/q/Desktop/PigsAndBulls.py", line 52, in <module>
if answer.keysym == 'Return':
AttributeError: 'str' object has no attribute 'keysym'
Also, If I press any other key, it simply prints in Idle and the program does not exit.
By the way, I know there has to be a better way to program this using lists or dictionaries, but this is all I know how to do.
pressing enter would result in a zero-length word. make that your first check.
however, if you want to catch a single keyhit, like getch() in C, it's a lot more complicated, e.g. https://stackoverflow.com/a/6599441/493161
another alternative would be to trap ^C (control-C):
try:
answer = raw_input('Control-C to exit, <ENTER> to play again: ')
if len(answer) > 0:
raise(ValueError('Unexpected input'))
else:
continue
except (KeyboardInterrupt, ValueError):
sys.exit(0)