Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/362.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python从文件中读取特殊字符并打印它们_Python_File Io - Fatal编程技术网

python从文件中读取特殊字符并打印它们

python从文件中读取特殊字符并打印它们,python,file-io,Python,File Io,我想做的是: 我有一个包含简单html代码的文件: Content-type:text/html\r\n\r\n <html> <head> <meta charset=\"utf-8\"/> <title>DNS checker CGI script</title> . . 提前感谢您的帮助我相信您也需要设置编码。让我知道这是否适合你 f = open('/var/www/html/dns-checker/dns_not_corre

我想做的是:

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

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

提前感谢您的帮助

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

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

所以,这是你的问题:

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>

问题是什么?您是否尝试过
s.replace(r'\r\n','\r\n')
?我正试图找到一种更具普遍性的方法…非常感谢,它很有效!请你解释一下为什么我需要使用编解码器。escape_decode()?
f = open('/var/www/html/dns-checker/dns_not_correct.txt', 'r', encoding='utf-8-sig')
   print(f.read(), end='')
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>
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>