简体   繁体   中英

reading output from a text file

For instance, the following test.py script can be displayed at ../cgi-bin/test.py , but is there a way I could display the same output from a text file (like test.txt) instead of text.py, so that the url would be something like ../text.txt ?

--- test.py ---

def printxt():
  print "Content-Type: text/plain"
  print """my text here..."""

如果将浏览器指向www.yoursite.com/yourtext.txt,您会发现大多数浏览器完全能够显示文本文件,而无需任何其他代码。

You appear to be asking if web servers can serve, and web browsers display text files. The answer is yes. Put the text file underneath DOCUMENTROOT and it's all good.

Or did I misunderstand the question?

If you want to use Python to do this in the context of a larger program (the example you just gave would be useless if that's all that you wanted it to do), you can simply use the standard:

file = open("filename.txt", "r")
for line in file:
  print line

You already know about the Content-type line which of course would be the same.

If the file is small enough to be read into memory all at once without causing problems, you can use "print file.read()" in order to have file.read() read the entire file as a single string, then print that out.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM