I'm working on this coding assignment I had for a c++ class. For fun, I
decided to implement it in Python, and I'm done. Still, I found a
behaviour I can't explain:
The function loadfromfile

def loadfromfile(lines, fname):
    try:
        finput = file(fname, 'r')
        lines = []
        for line in finput:
            line = line[:-1]
            lines.append(line)
        finput.close()
        return lines
    except:
        print "Couldn't load from file %s" % (fname)

takes a file (referenced by fname) and appends each line of text in it
to a list called lines (a global var, see full code below).
Problem is, as soon as I leave the function, lines is empty. Even when
I'm returning it, non-empty. I tried putting a print statement just
before "return lines" and it shows the complete list (according to what
was in the file, obviously). But after that, the contents are emptied.
Modifying that function to

def loadfromfile(fname):
    try:
        finput = file(fname, 'r')
        global lines
        lines = []
        for line in finput:
            line = line[:-1]
            lines.append(line)
        finput.close()
        #return lines
    except:
        print "Couldn't load from file %s" % (fname)

works (with or without the return lines statements, that's why I
commented it), but I don't understand why. I know lists are modified in-
place, so I'd imagine it would work in the first case too.

-------------------------------
Full code below:

#!/usr/bin/env python
# pysimpleditor: a concept - text editor

# Global vars:
lines = []                      # Holds the lines of text in memory.

# Functions:

# insertline inserts text into lines _before_ the index linenumber.
def insertline(lines, linenumber):              
        try:
                        line = int(linenumber)
        except: 
                print "not a valid line number"
        text = raw_input("Input text: ")
        lines.insert(line, text)
        
#deleteline deletes the line of text at lines[linenumber]
def deleteline(lines, linenumber):
        try:
                line = int(linenumber)
        except: 
                print "not a valid line number"
        lines.pop(line)

# Print the lines to the screen
def printlines(lines):
        for line in lines:
                print line
                
# Saves list lines to file fname.
def savetofile(lines, fname):
        try:
                foutput = file(fname, 'w')
                for line in lines:
                        line = line + '\n'
                        foutput.write(line)
                foutput.close()

        except:
                print "Couldn't open file %s for saving" % (fname)

# Loads text from fname into list lines.
def loadfromfile(fname):
        try:
                finput = file(fname, 'r')
                global lines
                lines = []
                for line in finput:
                        line = line[:-1]
                        lines.append(line)
                finput.close()
        except:
                print "Couldn't load from file %s" % (fname)
        

def printhelp():
        print """
pysimpleeditor: A simple text editor.
Use:
In: inserts a line of text before line n.
En: deletes line n.
V:  prints all lines on the screen.
S:  saves the lines of text to a file.
C:  loads text from a file.
H:  this message.
F:  exit the program.
"""

#The program:
while True:
        choice = raw_input("Please enter a command (h for help): ")
        choice = choice.upper()                 # Why bother the user with caps 
or uncaps?
        
        if choice[0] == 'I':                    # Line addition
                insertline(lines, choice[1:])

        elif choice[0] == 'E':                  # Line deletion
                deleteline(lines, choice[1:])

        elif choice[0] == 'V':                  # Text visualization
                for line in lines:
                        print line
                        
        elif choice[0] == 'S':                  # Save text to file
                fname = raw_input("Enter a filename to save: ")
                savetofile(lines, fname)
                
        elif choice[0] == 'C':                  # Load text from file, 
_replaces_ list!
                fname = raw_input("Enter a filename to load: ")
                loadfromfile(fname)
                        
        elif choice[0] == 'H':
                printhelp()
                
        elif choice[0] == 'F':                          # Exits the program
                break
                
        else:
                print "%s is not a valid command. Press h for help" % 
(choice[0])

--------------------------------
-- 
Adriano Varoli Piazza
The Inside Out: http://moranar.com.ar
MSN: [EMAIL PROTECTED]
ICQ: 4410132

_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to