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

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? :)

April 23rd, 2010, 10:14 AM

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).

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

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.

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

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.

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.

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