4 Replies - 4340 Views - Last Post: 29 December 2009 - 03:30 AM Rate Topic: -----

#1 programmingnoob2013  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 06-December 09

File reading by user input

Posted 06 December 2009 - 05:14 PM

So I was trying to ask for user input of a file name and then using that file to open and average numbers in the file. My question is why when I run the code in IDLE and I input the file name 'data.dat' I get an NameError message saying Name 'data' is not defined here is the code
file1 = open(input (str("Please enter the name of the file you wish to open:" )),"r")## Open the file and "r" read it
		emp = 0
		y = 0
		for x in file1:
			x = x[0:-1] ## Take the whole 1st value.
			x = float(x)## Convert from string to number
			x = x + emp ## Add it to the zero
			y = y + 1.0 ## Add one to the y to account for each value inputed.
			emp = x ## This will add the old value to the new value
			convert_float(y)
		print "Here is the average of the numbers inputed",x / y
[size=2]

Is This A Good Question/Topic? 0
  • +

Replies To: File reading by user input

#2 eker676  Icon User is offline

  • Software Engineer
  • member icon

Reputation: 378
  • View blog
  • Posts: 1,833
  • Joined: 18-April 09

Re: File reading by user input

Posted 09 December 2009 - 01:49 PM

I think this is python.

To open files in python you need to use this syntax:
f = file(raw_input("Enter filename: "), 'r')
#...

Was This Post Helpful? 0
  • +
  • -

#3 rmccaffe  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 18-December 09

Re: File reading by user input

Posted 18 December 2009 - 06:26 PM

here's a pretty easy way

fname = raw_input('Enter filename...')

fileObject = open(fname, 'r')
Was This Post Helpful? 0
  • +
  • -

#4 Tshiknn  Icon User is offline

  • New D.I.C Head

Reputation: 4
  • View blog
  • Posts: 20
  • Joined: 18-October 09

Re: File reading by user input

Posted 19 December 2009 - 10:45 PM

The problem here is simple. You used the "input()" function, which takes a input to the user and immediately converts it into Python code. What you need is to change "input" to "raw_input". raw_input asks the user for input and returns a string.
Was This Post Helpful? 0
  • +
  • -

#5 chemicalfan  Icon User is offline

  • D.I.C Head

Reputation: 4
  • View blog
  • Posts: 88
  • Joined: 16-October 09

Re: File reading by user input

Posted 29 December 2009 - 03:30 AM

View Postrmccaffe, on 18 Dec, 2009 - 05:26 PM, said:

here's a pretty easy way

fname = raw_input('Enter filename...')

fileObject = open(fname, 'r')


This is the way (except 'fileObject' should be 'file1' in your example)
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1