开发者

reading output from a text file

开发者 https://www.devze.com 2023-02-14 01:16 出处:网络
For instance, the following test.py script can be displayed at ../cgi-bin/test.py, but is there a way I could dis开发者_如何学Pythonplay the same output from a text file (like test.txt) instead of tex

For instance, the following test.py script can be displayed at ../cgi-bin/test.py, but is there a way I could dis开发者_如何学Pythonplay 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..."""


If you point your browser to www.yoursite.com/yourtext.txt, you'll discover that most browsers are fully capable of displaying text files without any additional code.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消