I need to know which encoding it support but it's not in the documentation:
https://docs.python.org/3/library/csv.html
Here are the format I want to support:
ANSI
UTF-8
UNICODE
win1251
UTF-16LE
I there like a inclusive list that I can use to build my UI on?
EDIT: My files are on a external FTP server uploaded by user so they will not use my system default encoding. They can be in any format. I need to tell the user what encoding I support.
csv is not encoding-aware. Use open() for that.
From the docs you linked:
Since open() is used to open a CSV file for reading, the file will by default be decoded into unicode using the system default encoding (see locale.getpreferredencoding()). To decode a file using a different encoding, use the encoding argument of open:
import csv
with open('some.csv', newline='', encoding='utf-8') as f:
reader = csv.reader(f)
for row in reader:
print(row)
The same applies to writing in something other than the system default encoding: specify the encoding argument when opening the output file.
For which encodings are supported, see the docs for open():
encoding is the name of the encoding used to decode or encode the file. This should only be used in text mode. The default encoding is platform dependent (whatever locale.getpreferredencoding() returns), but any text encoding supported by Python can be used. See the codecs module for the list of supported encodings.
I'm trying to get a Python 3 program to do some manipulations with a text file filled with information. However, when trying to read the file I get the following error:
Traceback (most recent call last):
File "SCRIPT LOCATION", line NUMBER, in <module>
text = file.read()
File "C:\Python31\lib\encodings\cp1252.py", line 23, in decode
return codecs.charmap_decode(input,self.errors,decoding_table)[0]
UnicodeDecodeError: 'charmap' codec can't decode byte 0x90 in position 2907500: character maps to `<undefined>`
The file in question is not using the CP1252 encoding. It's using another encoding. Which one you have to figure out yourself. Common ones are Latin-1 and UTF-8. Since 0x90 doesn't actually mean anything in Latin-1, UTF-8 (where 0x90 is a continuation byte) is more likely.
You specify the encoding when you open the file:
file = open(filename, encoding="utf8")
If file = open(filename, encoding="utf-8") doesn't work, try
file = open(filename, errors="ignore"), if you want to remove unneeded characters. (docs)
Alternatively, if you don't need to decode the file, such as uploading the file to a website, use:
open(filename, 'rb')
where r = reading, b = binary
As an extension to #LennartRegebro's answer:
If you can't tell what encoding your file uses and the solution above does not work (it's not utf8) and you found yourself merely guessing - there are online tools that you could use to identify what encoding that is. They aren't perfect but usually work just fine. After you figure out the encoding you should be able to use solution above.
EDIT: (Copied from comment)
A quite popular text editor Sublime Text has a command to display encoding if it has been set...
Go to View -> Show Console (or Ctrl+`)
Type into field at the bottom view.encoding() and hope for the best (I was unable to get anything but Undefined but maybe you will have better luck...)
TLDR: Try: file = open(filename, encoding='cp437')
Why? When one uses:
file = open(filename)
text = file.read()
Python assumes the file uses the same codepage as current environment (cp1252 in case of the opening post) and tries to decode it to its own default UTF-8. If the file contains characters of values not defined in this codepage (like 0x90) we get UnicodeDecodeError. Sometimes we don't know the encoding of the file, sometimes the file's encoding may be unhandled by Python (like e.g. cp790), sometimes the file can contain mixed encodings.
If such characters are unneeded, one may decide to replace them by question marks, with:
file = open(filename, errors='replace')
Another workaround is to use:
file = open(filename, errors='ignore')
The characters are then left intact, but other errors will be masked too.
A very good solution is to specify the encoding, yet not any encoding (like cp1252), but the one which has ALL characters defined (like cp437):
file = open(filename, encoding='cp437')
Codepage 437 is the original DOS encoding. All codes are defined, so there are no errors while reading the file, no errors are masked out, the characters are preserved (not quite left intact but still distinguishable).
Stop wasting your time, just add the following encoding="cp437" and errors='ignore' to your code in both read and write:
open('filename.csv', encoding="cp437", errors='ignore')
open(file_name, 'w', newline='', encoding="cp437", errors='ignore')
Godspeed
for me encoding with utf16 worked
file = open('filename.csv', encoding="utf16")
For those working in Anaconda in Windows, I had the same problem. Notepad++ help me to solve it.
Open the file in Notepad++. In the bottom right it will tell you the current file encoding.
In the top menu, next to "View" locate "Encoding". In "Encoding" go to "character sets" and there with patiente look for the enconding that you need. In my case the encoding "Windows-1252" was found under "Western European"
Before you apply the suggested solution, you can check what is the Unicode character that appeared in your file (and in the error log), in this case 0x90: https://unicodelookup.com/#0x90/1 (or directly at Unicode Consortium site http://www.unicode.org/charts/ by searching 0x0090)
and then consider removing it from the file.
def read_files(file_path):
with open(file_path, encoding='utf8') as f:
text = f.read()
return text
OR (AND)
def read_files(text, file_path):
with open(file_path, 'rb') as f:
f.write(text.encode('utf8', 'ignore'))
In the newer version of Python (starting with 3.7), you can add the interpreter option -Xutf8, which should fix your problem. If you use Pycharm, just got to Run > Edit configurations (in tab Configuration change value in field Interpreter options to -Xutf8).
Or, equivalently, you can just set the environmental variable PYTHONUTF8 to 1.
for me changing the Mysql character encoding the same as my code helped to sort out the solution. photo=open('pic3.png',encoding=latin1)
I have a file with Unicode Japanese writing in it and I want to convert it to Shift-JIS and print it out to Shift-JIS encoded file. I do this:
with open("unikanji.txt", 'rb') as unikanjif:
unikanji = unikanjif.read()
sjskanji = unikanji.decode().encode('shift-jis')
with open("kanji.txt", 'wb') as sjskanjif:
sjskanjif.write(sjskanji)
It works except that when I open kanji.txt it always opens as an Ansi file, not Shift-JIS, and I see misc characters instead of Japanese. If I manually change the file encoding to Shift-JIS then the misc characters turn into the right Japanese characters. How do I make my program create the file as Shift-JIS to begin with?
"ANSI" is Microsoft's term for the default, localized encoding, which varies according to the localized version of Windows used. A Microsoft program like Notepad assumes "ANSI" for the encoding of a text file unless it starts with a byte order mark. Microsoft Notepad recogizes UTF-8, UTF-16LE and UTF-16BE BOMs.
Shift-JIS is a localized encoding, so you have to use an editor such as Notepad++ and manually configure it to Shift-JIS, as you have discovered. The file as you have written it is Shift-JIS-encoded, but unless the editor you use has some heuristic to detect the encoding it will have to be manually configured. You could also use Japanese Windows or change your localization default in your current Windows version and Shift-JIS might be the ANSI default.
By the way, converting encodings can be a little more straightforward. Below assumes the original file is UTF-8 and the target file will be shift-jis. utf-8-sig automatically handles and removes a byte order mark, if present.
with open('unikanji.txt',encoding='utf-8-sig') as f:
text = f.read()
with open('kanji.txt','w',encoding='shift-jis') as f:
f.write(text)
I use Python 3.4 on Win 7 and have the following problem:
I'd like to write a multiline unicode text to a text file which the user can open with the standard Windows Editor (I know ...) without any special instructions. I already figured out that this editor apparently needs a BOM to understand that the encoding is actually UTF-8:
with codecs.open(r'c:\configfile.txt', 'w', encoding='utf-8-sig') as cf:
cf.write("""Test1
Test2 öäüß
Test3""")
Now I noticed that with this code all newlines are written as 0x0a instead of 0x0d 0x0a, which the Windows Editor doesn't recognize, so it shows everything in one single line.
Long story short: What is a safe way to write a multiline unicode text string to a file that can be opened and edited with the Windows Editor?
With Python 3, you can simply use
with open(r'c:\configfile.txt', 'w', encoding='utf-8-sig') as cf:
...
which will open the file in "text" mode. That will use the correct line ending for the OS on which you run the script.
io.open() works the same way. codecs.open() always uses binary more, no translation of line endings will happen.
In Python 2, you could achieve the same effect by using wt as mode.
I have found a solution myself ... simply using io.open instead of codecs.open with the same parameters fixes the newline character issue:
with io.open(r'c:\configfile.txt', 'w', encoding='utf-8-sig') as cf:
cf.write("""Test1
Test2 öäüß
Test3""")
I've got a script that basically aggregates students' code files into one file for plagiarism detection. It walks through a tree of files, copying all file contents into one file.
I've run the script on the exact same files on my Mac and my PC. On my PC, it works fine. On my Mac, it encounters 27 UnicodeDecodeErrors (probably 0.1% of all files I'm testing).
What could cause a UnicodeDecodeError on a Mac, but not on a PC?
If relevant, the code is:
originalFile = open(originalFilename, "r")
newFile = open(newFilename, "a")
newFile.write(originalFile.read())
Figure out what encoding was used when saving that file. A safe bet is loading the file as 'utf-8'. If that succeeds then it's likely to be the correct encoding.
# try utf-8. If this fails, all bets are off.
open(originalFilename, "r", encoding="utf-8")
Now, if students are sending you these files, it's likely they just use the default encoding on their system. It is not possible to reliably guess the encoding. If they were using an 8-bit codec, like one of the ISO-8859 character sets, it will be almost impossible to guess which one was used. What to do then depends on what kind of files you're processing.
It is incorrect to read Python source files using open(originalFilename, "r") on Python 3. open() uses locale.getpreferredencoding(False) by default. A Python source may use a different character encoding; in the best case, it may cause UnicodeDecodeError -- usually, you just get a mojibake silently.
To read Python source taking into account the encoding declaration (# -*- coding: ...), use tokenize.open(filename). If it fails; the input is not valid Python 3 source code.
What could cause a UnicodeDecodeError on a Mac, but not on a PC?
locale.getpreferredencoding(False) is likely to be utf-8 on Mac. utf-8 doesn't accept arbitrary sequence of bytes as utf-8 encoded text. PC is likely to use a 8-bit character encoding that corrupts the input and produces a mojibake silently instead of raising an error due to a mismatched character encoding.
To read a text file, you should know its character encoding. If you don't know the character encoding then either read the file as a sequence of bytes ('rb' mode) or you could try to guess the encoding using chardet Python module (it would be only a guess but it might be good enough depending on your task).
I got the exact same problem. There seemed to be some characters in the file that gave a UnicodeDecodeError during readlines()
This only happened on my macbook, but not on a PC.
I solve the problem by simply skipping these characters:
with open(file_to_extract, errors='ignore') as f: reader = f.readlines()