0

I have a text file that I want to read in my cgi script that will appear with a new line in between each line but it is just coming up as one huge wall of text. I cant figure out where to put '\n'. I have tried multiple locations but none work. Here is my code.

cgitb.enable()

form = cgi.FieldStorage()

keyword = form.getvalue('keyword')

f = open('%s.txt' %keyword, 'r')

print 'Content-type: text/html\r\n\r'
print '<html>'
print '<title> keyword + "tweets" </title>'
print f.readlines()
print '</html>'

f.close()
1
  • What happens when I pass keyword='/home/username/Desktop/file.txt? Or is this some internal script? Commented Dec 13, 2012 at 0:27

2 Answers 2

3

By default, HTML treats newline characters as if they were whitespace. Convert those into <br> elements, or wrap your text in a <pre> element, or make sure white-space handling in CSS is appropriate.

Also, print f.readlines.join('\n') or print f.read() (or print f.readlines().join('<br>') if you go with the first choice); otherwise you should be getting the repr for the list.

Sign up to request clarification or add additional context in comments.

2 Comments

Sorry a little confused on what to do. Wrap what text in a <pre> element? Thanks for your answer btw
@Shmoe: The text you are trying to display and have problems breaking with newlines.
0

If you really want the output to appear as plain text then it's much easier to simply set the value of the Content-Type header to "text/plain" instead of "text/html" and then most browsers will simply render your text without the need for interspersed HTML.

Please note that if you DO want to generate HTML you should incude an opening and closing <BODY> tag around the file contents (unless they happen to be present in the file).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.