PDA

View Full Version : Is it possible to print out the text from a .txt file in pyhton?



jakeeee
April 23rd, 2010, 10:07 AM
For example..

print "text.txt"

Then it would print out the contents of the text file.
i know that wouldnt work, but like thats what I want it to do..
Any ideas fellow ubuntu users? :)

Compyx
April 23rd, 2010, 10:14 AM
http://wiki.python.org/moin/BeginnersGuide

nvteighen
April 23rd, 2010, 01:29 PM
Well, it's one of the first things you usually learn in Python. Look up the 'open()' built-in function (not 'os.open()' which is something else).

wmcbrine
April 23rd, 2010, 06:01 PM
print "text.txt"print file("text.txt").read()

soltanis
April 23rd, 2010, 07:29 PM
Python list comprehensions: oh exploitable.



import sys

def write(x):
sys.stdout.write(str(x) + "\n")

[write(x) for x in file("file.txt").readlines()]


Not actually useful though, you should really use the method mentioned above this post. Just proving that there's always another (convoluted, yet somehow more functionally satisfying) way to do it.

lavinog
April 23rd, 2010, 11:21 PM
print open('textfile.txt').read()




open(...)
open(name[, mode[, buffering]]) -> file object

Open a file using the file() type, returns a file object. This is the
preferred way to open a file.

Not sure why it is preferred though.

wmcbrine
April 24th, 2010, 02:07 AM
Personally I prefer to use "file" instead of "open" whenever I don't match it with an explicit "close", but that's just me.

jakeeee
April 24th, 2010, 09:05 AM
Thanks guys(: