2017-06-12 50 views
2

我试图做的是以下几点:蟒蛇从文件中读取特殊字符,并打印出来

我有一个简单的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='') 

在此先感谢您的帮助

+0

问题是什么? https://stackoverflow.com/help/how-to-ask – wwii

+0

你试过's.replace(r'\ r \ n','\ r \ n')'?我试图找到更通用的方式... –

回答

0

我相信你需要设置编码为好。让我知道这是否适合你!

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

所以,这里是你的问题:

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> 
+0

非常感谢,它的工作原理!您能否向我解释为什么我需要使用codecs.escape_decode()? – martinpetro111

相关问题