python read special characters from a file and print them

时间:2017-06-12 16:51:51

标签: python file-io

What I'm trying to do is the following:

I have a file with simple html code:

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

I'd like to read this file and print its content with special characters (\n,\r,%...) , so the output would look like this:

Content-type:text/html


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

My python code:

#!/usr/bin/python

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

Thanks in advance for your help

2 个答案:

答案 0 :(得分:0)

I believe you need to set the encoding as well. Let me know if this works for you!

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

答案 1 :(得分:0)

So, here's your problem:

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>

I believe the most generalizable solution is to use 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>