i have probably rather simple question. however, i am just starting to use python and it just drives me crazy. i am following the instructions of a book and would like to open a simple text file. the code i am using:
import sys
try:
d = open("p0901aus.txt" , "W")
except:
print("Unsucessfull")
sys.exit(0)
i am either getting the news, that i was unsucessfull in opening the document or pop up appears saying:
(unicode eror) 'unicodeescape' codec can't decode bytes in position 2-4: truncated \UXXXXXXXX escape
i have no clue what the problem is. i tried to save the document in different codes, tried different path...always the same problem
does anybody know any help?
thank you very much in advance,
georg ps: i am using windows vista
(unicode eror) 'unicodeescape' codec can't decode bytes in position 2-4: truncated \UXXXXXXXX escape
This probably means that the file you are trying to read is not in the encoding that open() expects. Apparently open() expects some Unicode encoding (most likely UTF-8 or UTF-16), but your file is not encoded like that.
You should not normally use plain open() for reading text files, as it is impossible to correctly read a text file (unless it's pure ASCII) without specifying an encoding.
Use codecs instead:
import codecs
fileObj = codecs.open( "someFile", "r", "utf-8" )
u = fileObj.read() # Returns a Unicode string from the UTF-8 bytes in the file
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With