简体   繁体   English

如何使用python源文件的'coding'标头正确读取其内容?

[英]How can use the 'coding' header of a python source file to read its contents properly?

Python source files often come with a coding header similar to the following Python源文件通常带有类似于以下内容的coding标头

# -*- coding: iso-8859-1 -*-

How can I this line to properly parse the contents of such a file? 我如何在这行代码中正确解析此类文件的内容? Is there a better way than manually opening the file in binary mode, reading one line, and checking if it contains the header? 有没有比以二进制模式手动打开文件,读取一行并检查它是否包含标题更好的方法? Is there a library that does this? 有图书馆这样做吗?


Background: this comes in the context of fixing this bug , which crashes elpy when used in conjunction with python3 and importmagic. 背景:这是在修复此bug的背景下进行的,当与python3和importmagic结合使用时,elpy会崩溃。 The code that I'm trying to fix uses 我要修复的代码使用

with open(filename) as fd:
    success = subtree.index_source(filename, fd.read())

and crashes on non-utf-8 files. 并在非utf-8文件上崩溃。 Ideally I would like to keep changes to a minimum. 理想情况下,我希望将更改减到最少。

There is tokenize.open() that does exactly that: it opens a Python source file using the character encoding specified in the coding header ( encoding declaration ). tokenize.open()可以做到这一点:它使用coding标头( 编码声明 )中指定的字符编码打开Python源文件。

You could decode on-the-fly remote Python files too . 您也可以实时解码远程Python文件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何正确解析 python 中的文件,并将其内容保存到字典 - How to properly parse a file in python, and save its contents to a dictionary 如何使用python读取文本文件并检查其内容 - How to read a text file and check against its contents with python 如何将shell命令传递到文件中并使用python读取其内容? - How to Pipe shell command into a file and read its contents using python? 如何提取 gzip 文件并在 python 中的 dataframe 中读取其内容 - How to extract a gzip file and read its contents in a dataframe in python 如何使用 Python 将文件夹中的 all.txt 文件和 append 其内容读取到 one.txt 文件中? - How to read all .txt files in a folder and append its contents into one .txt file, using Python? 如何读取文件的内容并将其转换为python中的字典 - how to read the contents of file and convert it into dictionary in python 如何使用 Python 读取 URL 的内容? - How can I read the contents of an URL with Python? 如何加载csv文件并将其内容存储在python中的(numpy)数组中? - How can I load a csv file and store its contents into an (numpy) array in python? python 脚本可以将自己的内容输出到另一个文件吗? - Can a python script output its own contents to another file? Python:是否可以在不将其内容加载到RAM的情况下写入文件? - Python: Can I write to a file without loading its contents in RAM?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM