-1

I'm running a program that reads a Dictionary off a file called questions.txt.

{
1:{0:'question',1:{1:'answer1a',2:'answer1b'},2:'answer2'},
2:{0:'question',1:'answer1',2:'answer2'},
3:{0:'question',1:'answer1',2:'answer2'},
4:{0:'question',1:'answer1',2:'answer2'}
}

I'm using this code from my file dictict.pyw to read parts of the Dictionary.

fQDict = open("questions.txt", "r")
QDict = " "
for i in fQDict.read().split():
    QDict += i
fQDict.close()
QDict = eval(QDict)

print(QDict)
print(QDict[1])
print(QDict[1][0])
print(QDict[1][1])
print(QDict[1][1][1])

When I run the program python throws an error saying source code string cannot contain null bytes at the QDict = eval(QDict) line, why?

AMC
  • 2,642
  • 7
  • 13
  • 35
  • The error is on the `eval` line? I ran your code and could not reproduce. – tdelaney Apr 23 '20 at 19:58
  • The error is occurring on the eval line, I updated the post. – gamers beware Apr 23 '20 at 20:02
  • Your real `questions.txt` has a null byte in it. You could `open('questions.txt').read().find('\x00')` to figure out where. BTW, there is no need to split / rebuild the text. You can just eval. – tdelaney Apr 23 '20 at 20:05
  • How exactly would I eval the file? – gamers beware Apr 23 '20 at 20:57
  • I assume it did have nulls? The first question is why that happens. You could `eval(open('questions.txt').read().replace("\x00", ""))` ... i think that would work. But since there are unexpected Nulls, the file itself could be corrupted, triggering the "Garbage In" rule. – tdelaney Apr 23 '20 at 20:59
  • `ast.ast_literal_eval` is considered the safer way to go. – tdelaney Apr 23 '20 at 21:00
  • Please provide a [mcve], as well as the entire error message. A few notes: Variable and function names should generally follow the `lower_case_with_underscores` style. Use a context manager to handle file objects. Don't use `eval()` unless there is a solid reason to do so. Where does that dictionary in the file come from? – AMC Apr 23 '20 at 21:43

2 Answers2

1

Your file contains null byte characters

sed -i 's/\x0//g' null.txt

This should help to remove these characters from your file.

for more reference see: https://stackoverflow.com/a/2399817/230468

0xh3reticc
  • 101
  • 6
0

Thank you to everyone for the advise and answers. The solution i found was to change the file from wordpad to notepad, since wordpad embeds code into the file.

  • Wordpad writes Rich Text Format files. There are python modules that convert rtf to text but you are better off using notepad here. – tdelaney Apr 23 '20 at 21:16