how to open and print a txt in python.? code: from sys import argv script, filename = argv txt = open(filename) print "Here's your file %r:" % filename print txt.read() but it does no work..
look first of all when you open a file you need to specifiy the mode e.g f = open(filename, mode) modes are 'r+' , 'r' etc. so in your case 'r' mode will be best
@camouflage Did this solved your problem ?
@harsimran_hs4 but how can python find my txt..giving it the path ? or only the file name .
if you file and script are in the same folder then filename would do (eg. abc.txt) otherwise you need to specify full path
*your file
when you are done with a file, make sure you close it. looks like you are trying to use string formatting - yo might want to look at the docs and play around with it a bit in a shell: http://docs.python.org/2.7/library/stdtypes.html#str.format http://docs.python.org/2.7/library/stdtypes.html#string-formatting http://docs.python.org/2.7/library/string.html#formatstrings http://docs.python.org/2.7/library/stdtypes.html#string-formatting http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html#string-formatting http://dpaste.com/1305383/
@camouflage it would be better if you show the code
@harsimran_hs4 my code is on the above ..it tells me that the name of the file is not defined
what are you giving for filename in command prompt
@harsimran_hs4 oh i gives it test1. it tells no such file
is your file in the same folder ? if yes: give test1.txt else: give full path
harsimran_hs4 i try both .but...can u give me ur code piture..thank u ..
run using python test.py test.txt
oh .thank u very much. i knew
Welcome!!
Join our real-time social learning platform and learn together with your friends!