I have been working a solution for a game which creates stats for two different players then saves to a .txt, For some reason, unbeknownst to me a sytax error keeps on appearing, here ;
Traceback (most recent call last):
File "E:\CA2 solution.py", line 29, in <module>
json.dump(char_data,open("character_data.dat","wb"))
File "C:\Python33\lib\json\__init__.py", line 184, in dump
fp.write(chunk)
TypeError: 'str' does not support the buffer interface
Im not sure what is wrong but here is the code as well,
import random
char1=str(input('Please enter a name for character 1: '))
strh1=((random.randrange(1,4))//(random.randrange(1,12))+10)
skl1=((random.randrange(1,4))//(random.randrange(1,12))+10)
line = '%s has a strength value of %s and a skill value of %s'%(char1,strh1,skl1)
char2=str(input('Please enter a name for character 2: '))
strh2=((random.randrange(1,4))//(random.randrange(1,12))+10)
skl2=((random.randrange(1,4))//(random.randrange(1,12))+10)
line = '%s has a strength value of %s and a skill value of %s'%(char1,strh1,skl1)
char_data1 = {
"name":char1,
"STRENGTH":strh1,
"SKILL":skl1,
};
char_data2 = {
"name":char2,
"STRENGTH":strh2,
"SKILL":skl2,
};
char_data = [char_data1,char_data2]
import json
json.dump(char_data,open("character_data.dat","wb"))
char_data_loaded = json.load(open("character_data.dat"))
I don't know what is wrong, so if anyone does could they please help me and point it out and suggest a way to fix it ? Thanks !
You are giving a string input to a file opened in binary mode. json.dump serializes the char_data as a string as noted in the doc here
So open the file in w mode instead of wb and the error will be fixed.
Related
I am trying to translate a pdf document from english to french using google translation api and python, however I get a type error.
Traceback (most recent call last):
File "C:\Users\troberts034\Documents\translate_test\translate.py", line 42, in <module>
translate_document()
File "C:\Users\troberts034\Documents\translate_test\translate.py", line 33, in translate_document
f.write(response.document_translation.byte_stream_outputs)
TypeError: a bytes-like object is required, not 'Repeated'
I have a feeling that it has something to do with writing to the file as binary, but I open it as binary too so I am unsure what the issue is. I want it to take a pdf file that has english text and edit the text and translate it to french using the api. Any ideas whats wrong?
from google.cloud import translate_v3beta1 as translate
def translate_document():
client = translate.TranslationServiceClient()
location = "global"
project_id = "translatedocument"
parent = f"projects/{project_id}/locations/{location}"
# Supported file types: https://cloud.google.com/translate/docs/supported-formats
with open("C:/Users/###/Documents/translate_test/test.pdf", "rb") as document:
document_content = document.read()
document_input_config = {
"content": document_content,
"mime_type": "application/pdf",
}
response = client.translate_document(
request={
"parent": parent,
"target_language_code": "fr-FR",
"document_input_config": document_input_config,
}
)
# To output the translated document, uncomment the code below.
f = open('test.pdf', 'wb')
f.write(response.document_translation.byte_stream_outputs)
f.close()
# If not provided in the TranslationRequest, the translated file will only be returned through a byte-stream
# and its output mime type will be the same as the input file's mime type
print("Response: Detected Language Code - {}".format(
response.document_translation.detected_language_code))
translate_document()
I think there is a bug on the sample code (I'm assuming you got the sample from the Cloud Translate API documentation).
To fix your code, you do need to use response.document_translation.byte_stream_outputs[0]. So basically changing this line:
f.write(response.document_translation.byte_stream_outputs)
by:
f.write(response.document_translation.byte_stream_outputs[0])
then your code will work.
I'm new to python and I'm trying to loop through all 255 addresses to locate a specific bit of hardware over RS485. The hardware is attached, and it's address is supposed to be 0x25, but this is not the case, so I need to find what its address is.
So far I've got:
def Init_Sync_4 ():
GPIO.output(18,GPIO.HIGH)
ser.write([CID,0x17,0x20,0x01,0x14,0x1c,0x04,0x00,0x00,0x00,0x00,0x00,0x32,0x00,0x01,0x00,0x00,0x00,0x32,0x00,0x02,0x00,0x00,0$
time.sleep(0.007)
GPIO.output(18,GPIO.LOW)
and
ser=serial.Serial(port='/dev/serial0',baudrate=38400,stopbits=2,timeout=1)
GPIO.setmode(GPIO.BCM)
GPIO.setup(18,GPIO.OUT)
GPIO.output(18,GPIO.LOW)
for i in range(0xff):
CID = '0x{:02x}'.format(i).encode('ascii')
print "at address %s" % CID
Init_Sync_4()
time.sleep(0.05)
Init_2()
time.sleep(0.05)
Here CID is the address being built, which Init_Sync_4() uses in it's byte array in ser.write, but I keep getting the error:
at address 0x00
Traceback (most recent call last):
File "rs485_test_2.py", line 97, in <module>
Init_4()
File "rs485_test_2.py", line 40, in Init_4
ser.write([CID,0x17,0x20,0x01,0x14,0x1c,0x04,0x00,0x00,0x00,0x00,0x00,0x32,0x00,0x01,0x00,0x00,0x00,0x32,0x00,0x02,0x00,0x00,0x00,0x00])
File "/usr/lib/python2.7/dist-packages/serial/serialposix.py", line 518, in write
d = to_bytes(data)
File "/usr/lib/python2.7/dist-packages/serial/serialutil.py", line 66, in to_bytes
return bytes(bytearray(seq))
ValueError: string must be of size 1
I'm assuming that it's still being passed as a string, when it needs to be a single byte, but I'm lost at how the conversion would work. I've checked out some SO pages, that specify using .encode with or without params, but I'm either using it incorrectly, or it's not quite what I'm after. Any help is greatly appreciated! Thanks.
ser.write([CID,0x17,0x20,0x01, ...
CID is going into a list with a bunch of integers. But itself is a string.
You want to leave CID as an integer.
# CID = '0x{:02x}'.format(i).encode('ascii')
CID = i
for printJobString in logfile:
userRegex = re.search('(\suser:\s)(.+?)(\sprinter:\s)', printJobString)
if userRegex:
userString = userRegex.group(2)
pagesInt = int(re.search('(\spages:\s)(.+?)(\scode:\s)', printJobString).group(2))
above is my code, when I run this program in the module I end up getting,
Traceback (most recent call last):
File "C:\Users\brandon\Desktop\project3\project3\pages.py", line 45, in <module>
log2hist("log") # version 2.
File "C:\Users\brandon\Desktop\project3\project3\pages.py", line 29, in log2hist
pagesInt = int(re.search('(\spages:\s)(.+?)(\scode:\s)', printJobString).group(2))
AttributeError: 'NoneType' object has no attribute 'group'
I know this error means the search is returning None but I'm not sure how to handle this case. Any help would be appreciated, very new to python and still learning the basics.
I am writing a program that should print out the number of pages a user has.
180.186.109.129 code: k n h user: luis printer: core 2 pages: 32
is a target string, my python file is trying to create a data file that has one line for each user and contains the total number of pages printed
The reason it happens is because your regexp does not find anything and returns None
re.search('(\spages:\s)(.+?)(\scode:\s)') returns None
use an if statement to test if it's not None before you try to group
for printJobString in logfile:
userRegex = re.search('(\suser:\s)(.+?)(\sprinter:\s)', printJobString)
if userRegex:
userString = userRegex.group(2)
pagesInt = re.search('(\spages:\s)(.+?)(\scode:\s)', printJobString)
if pagesInt:
pagesInt = int(pageInts.group(2))
I have seen a lot of KeyCount Errors online but none of them quite match the troubles that I'm having. I am using feed parser to try and create a one run application that accesses all the URLs in a text file and outputs all the entries in each URL. When I run this code :
import feedparser as f
with open('addresses.rtf', 'r') as addresses:
for line in addresses:
d = f.parse(line)
print d["feed"]["title"]
print ""
print d.feed.subtitle
print ""
for post in d.entries:
print post.title
print post.link
print ""
I get this error message :
Traceback (most recent call last):
File "/Users/Josh/Desktop/Feed Parser Python Project/init.py", line 7, in <module>
print d["feed"]["title"]
File "build/bdist.macosx-10.6-intel/egg/feedparser.py", line 375, in __getitem__
return dict.__getitem__(self, key)
KeyError: 'title'
My text file is just a .rtf file that has a URL on each line (3 lines).
If someone could give us a hand please let me know and if you need any extra info please don't hesitate to ask. Any help is welcome. Thank you!
It's hard to tell exactly what is wrong here, but in the general case, any KeyError is because the data you are trying to access is not exactly what you expected. It's best to throw your assumptions out the window and take a close look at the actual data that your code is working with.
For debugging, I would recommend taking a close look at what happens before the error. What is the value of line as you read the file? Is it correct? What is the value of d? Did the call to f.parse(line) result in a valid object?
I am trying to make a simple password-storing program in Python, and it seems pretty simple so I am wondering if I am using shelve wrong.
I have the main .py file:
import shelve
passwords = shelve.open('./passwords_dict.py')
choice = raw_input("Add password (a) or choose site (c)?")
if choice[0] == 'a':
site_key = raw_input("Add for which site? ").lower()
userpass = raw_input("Add any info such as username, email, or passwords: ")
passwords[site_key] = userpass
else:
site = raw_input("Which site? ").lower()
if site in passwords:
print "Info for " + site + ": " + passwords[site]
else:
print site, "doesn't seem to exist!"
print "Done!"
passwords.close()
And the other file, passwords_dict.py, is just an empty dictionary.
But when I try to run the program, I get this error:
Traceback (most recent call last):
File "passwords.py", line 3, in <module>
passwords = shelve.open('passwords_dict.py')
File "/usr/lib/python2.7/shelve.py", line 239, in open
return DbfilenameShelf(filename, flag, protocol, writeback)
File "/usr/lib/python2.7/shelve.py", line 223, in __init__
Shelf.__init__(self, anydbm.open(filename, flag), protocol, writeback)
File "/usr/lib/python2.7/anydbm.py", line 82, in open
raise error, "db type could not be determined"
anydbm.error: db type could not be determined
When I try to use anydbm instead, I get this error:
Traceback (most recent call last):
File "passwords.py", line 3, in <module>
passwords = anydbm.open('passwords_dict.py')
File "/usr/lib/python2.7/anydbm.py", line 82, in open
raise error, "db type could not be determined"
anydbm.error: db type could not be determined
And when I try to use dbm instead, I get this error:
Traceback (most recent call last):
File "passwords.py", line 3, in <module>
passwords = dbm.open('./passwords_dict.py')
dbm.error: (2, 'No such file or directory')
What am I doing wrong? Is there another way to store a dictionary and still be able to extract keys using user input (rather than the entire dictionary, which I suppose is what pickle does)?
I think you're misunderstanding how the shelve module works. It opens a database file. When you try and open an existing file that contains a Python script, it's trying to detect what database type the file contains (since shelve supports multiple backend databases).
I think instead you want something like this:
import os
import shelve
curdir = os.path.dirname(__file__)
passwords = shelve.open(os.path.join(curdir, 'password_db'))
This will create a new file in the same directory as your script called password_db.<db> where <db> is an implementation-specific database file extension.
I've experienced this issue as well. It seems to be related to undocumented conditions for the filename argument of shelve.open. It is currently very intransparent (e.g. shelve.open("/tmp/tmphTTQLda") works while shelve.open("/tmp/tmphTTQLd") doesn't). Failure and success of variable filenames are hard to predict. I requested an explanation in form a documentation enhancement at http://bugs.python.org/issue23174.
In my case opening a persistent dict outside shelve and passing it to shelve.Shelve works, e.g. code
a = dumbdbm.open(tempfile.mkstemp()[1])
b = shelve.Shelf(dict=a)
and do with b what you'd have done with the return value of shelve.open.
There is one bug with anydb https://bugs.python.org/issue13007 that could not use the right identification for gdbm files.
So if you are trying to open a valid gdbm file with shelve and is thorwing that error use this instead:
mod = __import__("gdbm")
file = shelve.Shelf(mod.open(filename, flag))
More information on this question: shelve db type could not be determined, whichdb is not recognizing gdb