-1

I'm reading a book on basic python and need help translating this program. It will be my first program, so don't laugh at me please.

I need a step by step guide with this; when I click print and it says fname not found.


#!/usr/bin/env python

# 'makeTextFile.py -- create text file'

import os
ls = os.linesep

# get fileneame
while True:

    if os.path.exists(fname):
        print "ERROR: '%s' already exists" % fname
    else:
        break

# get file content (text) lines
all = []
print "\nEnter lines (' . ' by itself to quit). \n"

# loop until user terminates input
while True:
    entry = raw_input('> ')
    if entry == '.':
        break
    else:
        all.append(entry)

# write lines to file with proper line-ending
fobj = open(fname, 'w') 
fobj.writelines(['%s%s' % (x, ls) for x in all])
fobj.close()
print 'DONE'
Edwin
  • 1,938
  • 1
  • 19
  • 35
  • 1
    If this is your first program, you're being a bit ambitious. You should have a better understanding of basic Input/Output in a given programming language before attempting file operations (which are a more complex form of input/output). – Edwin Feb 29 '12 at 16:19

7 Answers7

2

You have to define the variable fname. To define a variable in Python, you just say variable_name=variable_value. If I were to type moo='cow', later when I type moo, it would return cow. In your case, it would be...

import os

ls = os.linesep
fname=raw_input('File path: ')

while True:
  if os.path.exists(fname):
    print "ERROR: '%s' already exists" % fname
    fname=raw_input('File path: ')
  else:
    break

By the way, your loop will just keep printing "ERROR" if the file path is wrong. You have to put the raw_input() inside of it also. You might want to look at the docs. There are tutorials there and documentation.

As for what this code does, it checks to if the file doesn't exist, and if it doesn't, then creates a new file with the file name, and then writes the user's input to the file.

CoffeeRain
  • 4,294
  • 4
  • 27
  • 49
  • Actually, this code checks to make sure the file _doesn't_ exist, then creates a new file with the file name, populated with the user's input. – Edwin Feb 29 '12 at 16:15
1

I have the same problem, using same book. Author forgot to insert

fname = raw_input("enter file name: ")

inside the while loop. So first you prompt user to enter filename then check if it exists, if it does, you prompt user again or else you break the loop and execute the rest of the code.

#!/usr/bin/env python

import os
ls = os.linesep

# get file name that doesn't exist yet

while True:
    fname = raw_input("enter file name: ")

    if os.path.exists(fname):
        print "ERROR: '%s' already exists" % fname
    else:
    break

all = []
print "\n Enter lines ('.' by itself quit) .\n"

# enter lines one by one until user terminates
while True:
    entry = raw_input('> ')
    if entry == '.':
        break
    else:
    all.append(entry)

fobj = open(fname, 'w')
fobj.writelines(['%s%s' % (x, ls) for x in all])
fobj.close()
print 'DONE'
michalu
  • 13
  • 5
1

All the answers here have already stated why you get an error message. So, I will predominantly focus on the line by line explanation of the program.

    #!/usr/bin/env python

This line specifies that the file is a python script and also specifies which python environment is being used.

Read this for better understanding:

Why do people write #!/usr/bin/env python on the first line of a Python script?

The next line is

   # 'makeTextFile.py -- create text file'

This is a comment line which specifies what this current script does.

    import os
    ls = os.linesep

This line is importing a module named os. A module is a file consisting of Python code. A module can define functions, classes and variables.In this case, the module imported provides a way of using operating system dependent functionality. It then stores the line separator(a string that separates one line from another) used in files (specific to that operating system). Read about os modules here:- https://docs.python.org/2/library/os.html

After this step, you have to get the fname (inside the loop) as stated in one of the answers. 'fname' is a variable where the filename to be created is stored.

   while True:
       if os.path.exists(fname):
           print "ERROR: '%s' already exists" % fname
       else:
           break 

This is a while loop (a repeating code block that continues till the condition (here True) is true). It checks if a file with that specific name exists.This is done with the help of the os.path manipulator . If it exists , then there is an Error which is printed inside the (if:) block and this loop repeats till a filename that does not exist is encountered. In that case (filename does not exist ) , break is encountered which breaks out of the while loop.

    all = []

This specifies a list data structure named all . The motivation of this declaration is that it will store all the user input .

   print "\nEnter lines (' . ' by itself to quit). \n"

This prints a line into the interpreter screen , that suggests the user to input their message.It is a hint to the user as to what is expected of them. It also specifies that to quit enter '.' only.

  while True:
      entry = raw_input('> ')
      if entry == '.':
          break
      else:
          all.append(entry)     

This is another loop which iteratively takes user input and appends ( adds into the list) to all . If a single '.' is encountered, the loop breaks and the user input is over. Having finished this, the next step is to write it into the file. The next set of code is written for that purpose.

    fobj = open(fname, 'w')
    fobj.writelines(['%s%s' % (x, ls) for x in all])
    fobj.close()

The file is opened in 'write' mode . Mode specifies the purpose for which the file is opened. Here ,'w' specifies that the file opened is only for writing purpose. The file opened is accessed by the variable fobj. The next line then writes the contents of all(the list) into the file. 'for x in all' iterates through each item inside the list. This x and the line separator (stored in ls) is then written . Finally, after all the contents are written, the file is closed.

The author then prints

   print 'DONE'

It just shows that the entire work is over. This is a redundant step and can be avoided.

Correction in the approach will be appreciated.

Community
  • 1
  • 1
Echo
  • 419
  • 6
  • 18
0

You need to define fname try:

fname = raw_input ('Enter file name > '

EDIT: Also as many people have said on this thread be carful about running programs that you do not understand. From a verified book is normally safe but still please make sure you fully understand the program/s you are running before anything.


Leo Cornelius (HTH) Simplistic Panda (Don't ask)

  • Sorry I now notice this is a dead thread.I have too little reputation but I recommend a flag as it is quite a personal question and 'not going to benefit communtiy' if you want to put it that way – Leo Cornelius Apr 08 '18 at 14:38
0

you have to define the variable fname which you never do, so define it and it should work. also in the future also post the error you get

Zimm3r
  • 3,177
  • 3
  • 30
  • 48
-1

There's an error in your program. You should have to set the value of fname, otherwise you'll get an error as shown below:

NameError: name 'fname' is not defined

JasonMArcher
  • 12,386
  • 20
  • 54
  • 51
iamjayp
  • 366
  • 4
  • 15
-1

fname is the name of a file you are checking exists. If it does not exist creates it. however there are much simpler ways of doing said action in python 3.7

sam
  • 15,535
  • 21
  • 72
  • 109
  • Technically correct, but someone who doesn't understand programming/is new to it probably wouldn't get your message. Plus, this is really short. Please clarify and expand. – Edwin Feb 29 '12 at 16:17
  • I understand, only to learn is copy and paste and play with the code so that's what i am doing. when i program this code it seems to be in a infinite loop is that what it was designed for? – liban shire Feb 29 '12 at 18:22
  • @libanshire Read my answer. I explained that if the file exists, then it keeps looping through telling you that it exists. – CoffeeRain Feb 29 '12 at 20:43
  • so it writes the user input in the file? where is the file located by the way? and how do i write on? – liban shire Mar 01 '12 at 18:25
  • @liban : just before while statement, write as filename = 'test.txt' now after program run, it will creates test.txt in same directory. accept & close the answer if you get the same by clicking right mark infront of my answer. – sam Mar 02 '12 at 04:23