【问题标题】:python read special characters from a file and print thempython从文件中读取特殊字符并打印它们
【发布时间】:2017-06-12 16:51:50
【问题描述】:

我想要做的是:

我有一个带有简单 html 代码的文件:

Content-type:text/html\r\n\r\n
<html>
<head>
<meta charset=\"utf-8\"/>
<title>DNS checker CGI script</title>
.
.

我想读取这个文件并用特殊字符 (\n,\r,%...) 打印它的内容,所以输出应该是这样的:

Content-type:text/html


<html>
<head>
<meta charset="utf-8"/>

我的python代码:

#!/usr/bin/python

f = open('/var/www/html/dns-checker/dns_not_correct.txt', 'r')
print(f.read(), end='')

提前感谢您的帮助

【问题讨论】:

标签: python file-io


【解决方案1】:

我相信您也需要设置编码。让我知道这是否适合您!

f = open('/var/www/html/dns-checker/dns_not_correct.txt', 'r', encoding='utf-8-sig')
   print(f.read(), end='')

【讨论】:

    【解决方案2】:

    所以,这是你的问题:

    In [17]: mystring = r"""Content-type:text/html\r\n\r\n
        ...: <html>
        ...: <head>
        ...: <meta charset=\"utf-8\"/>
        ...: <title>DNS checker CGI script</title>"""
    
    In [18]: print(mystring)
    Content-type:text/html\r\n\r\n
    <html>
    <head>
    <meta charset=\"utf-8\"/>
    <title>DNS checker CGI script</title>
    

    我相信最通用的解决方案是使用codecs

    In [20]: import codecs
    
    In [21]: codecs.escape_decode(mystring)
    Out[21]:
    (b'Content-type:text/html\r\n\r\n\n<html>\n<head>\n<meta charset="utf-8"/>\n<title>DNS checker CGI script</title>',
     108)
    
    In [22]: print(codecs.escape_decode(mystring)[0])
    b'Content-type:text/html\r\n\r\n\n<html>\n<head>\n<meta charset="utf-8"/>\n<title>DNS checker CGI script</title>'
    
    In [23]: print(codecs.escape_decode(mystring)[0].decode())
    Content-type:text/html
    
    
    <html>
    <head>
    <meta charset="utf-8"/>
    <title>DNS checker CGI script</title>
    

    【讨论】:

    • 非常感谢,它有效!你能解释一下为什么我需要使用 codecs.escape_decode() 吗?
    猜你喜欢
    • 2021-06-11
    • 1970-01-01
    • 2014-07-27
    • 2015-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-02
    • 1970-01-01
    相关资源
    最近更新 更多