Calling external text-files (newb)

Michael Hartl mhartl at post.harvard.edu
Mon Feb 28 17:15:34 EST 2005


There are two problems: (1) by quoting 'source', you refer to a string
literal, not the variable you defined via raw_input; (2) you have not
defined the variable 'input', so there's no way to call the 'read'
method on it.

Try this instead:

source_path = raw_input('file path: ')
s = open(source_path).read()
print s

The default behavior of 'open' includes 'r' implicitly.

You can also use the function 'file', which is a synonym for 'open':

s = file(source).read()

Be warned that using the same syntax when writing files is dangerous;
in that case you should create a file object and explicitly close it.

f = file('a_copy', 'w')
f.write(s)
f.close()

HTH,

Michael

--
Michael D. Hartl, Ph.D.
CTO, Quark Sports LLC
http://quarksports.com/




More information about the Python-list mailing list