3 Replies - 635 Views - Last Post: 20 March 2015 - 02:09 PM Rate Topic: -----

#1 Maskman   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 30
  • Joined: 17-February 15

can't read from the file

Posted 20 March 2015 - 01:23 AM

Sorry, for such stupid question, but I can't understand it... I wrote a function that would open a file and read a link that is in it, turn it into a variable and prints this variable, (coz, some links are really huge, + it's possible to make a mistake while typing). The function is really small but it's a pain in the a$#...
def o_r():
	fname=raw_input('enter a file name: ')
	ffname=fname+'.txt'
	fhand=open(ffname)
	readf=fhand.read()
	for link in readf:
		print link
	fhand.close()

o_r()
inp=raw_input('fin ')



Is This A Good Question/Topic? 0
  • +

Replies To: can't read from the file

#2 djjeavons   User is offline

  • D.I.C Regular
  • member icon

Reputation: 114
  • View blog
  • Posts: 417
  • Joined: 09-January 09

Re: can't read from the file

Posted 20 March 2015 - 01:33 AM

Hi

At the moment, you are using the .read() method which will read each character in the file one by one. Instead use readlines() to read a line at a time:

fhand = open("link.txt")
for line in fhand.readlines():
  print line

fhand.close()




HTH
Was This Post Helpful? 1
  • +
  • -

#3 baavgai   User is offline

  • Dreaming Coder
  • member icon


Reputation: 7506
  • View blog
  • Posts: 15,556
  • Joined: 16-October 07

Re: can't read from the file

Posted 20 March 2015 - 03:14 AM

fhand=open(ffname) # this is a file handle
readf=fhand.read() # this is a bit of data read from a file
for link in readf: # you're trying iterate over the data you read!



There are a number of ways to iterate over the data in the file, but you need to make the file handle part of that loop.
Was This Post Helpful? 1
  • +
  • -

#4 witeboy724   User is offline

  • D.I.C Head
  • member icon

Reputation: 84
  • View blog
  • Posts: 208
  • Joined: 21-June 12

Re: can't read from the file

Posted 20 March 2015 - 02:09 PM

View Postdjjeavons, on 20 March 2015 - 01:33 AM, said:

fhand = open("link.txt")
for line in fhand.readlines():
  print line

fhand.close()


While you're learning about open() I'd like to also mention the with statement. It'll keep you from having to call .close() on the file and looks prettier. Djjeavon's code using with:
with open("link.txt") as fhand:
    for line in fhand.readlines():
        print line


Was This Post Helpful? 3
  • +
  • -

Page 1 of 1