-3

I am learning python from past weeks

from sys import argv
script,filename = argv 
print "We're delete the file %r" %filename
print "If you want to stop ctrl+c (^c)"
print "Please hit enter to continue"
raw_input(">_")
print "Opening file..."
filen = open(filename,'w')
print "Truncating your file...."
filen.truncate()
print "now in your file %r" %filen
print "Writing time write  something to your file"

line = raw_input("?")
print "write in progress..."
filen.write(line)
filen.write("\n end of document\n")
filen.close()

I want to view the contents of the file ,but when i use print filename or print filen it show name and open file on variable filen

be_good_do_good
  • 4,311
  • 3
  • 28
  • 42
root
  • 43
  • 1
  • 6

3 Answers3

0

you can read data using filen.read() or filen.readline() or filen.readlines()

1) read

fo = open(filename,read)
fo.seek(0, 0) #seek is used to change the file position.This requires only for read method
fo.read(10) #This reads 1st 10 characters
fo.close()

2) readline

fo = open(filename,read)
fo.readline() #This will read a single line from the file. You can add for loop to iterate all the data
fo.close()

3) readlines.

fo = open(filename,read)
fo.readline() #read all the lines of a file in a list 
fo.close()

Below document will give you better idea. https://docs.python.org/2/tutorial/inputoutput.html

Harsha Biyani
  • 7,049
  • 9
  • 37
  • 61
  • 1
    If you're writing first you'll want to [`.seek(0)`](https://docs.python.org/2/tutorial/inputoutput.html#methods-of-file-objects) before reading – GP89 Aug 23 '16 at 07:22
  • I added "$print filen.read() " I got IOError: File not open for reading so I ve added "$open(filen,'r') " but this time i got >> open(filen,'r') TypeError: coercing to Unicode: need string or buffer, file found – root Aug 23 '16 at 09:43
0

If you want to print the content of the file you opened, just use: print filen.read().

Moran Neuhof
  • 426
  • 4
  • 6
  • I added "$print filen.read() " I got IOError: File not open for reading so I ve added "$open(filen,'r') " but this time i got >> open(filen,'r') TypeError: coercing to Unicode: need string or buffer, file found – root Aug 23 '16 at 09:43
  • For that you need to first open the file: `filen=open(filename, 'r')` and only then use: `print filen.read()` – Moran Neuhof Aug 24 '16 at 15:51
0

At its simplest:

from sys import argv
script,filename = argv 
with open(filename) as f:
    print f.readlines()

which dumps the files contents or:

from sys import argv
script,filename = argv 
with open(filename) as f:
    lines=f.readlines()
for line in lines:
    print line

which prints the lines out 1 by 1

Rolf of Saxony
  • 21,661
  • 5
  • 39
  • 60