2

I am a python newbie. I am trying to run this simple python example. I am wish to pass files and certain values as parameter to my function latcalc(). Could anyone suggest how I can pass my files and values as parameters. Or is there any better way/approach to do these things.

#!/usr/bin/python

# include the constants

min_length = 1
max_length = 30


# delays

delay = 100

# Speed of light 

c_vaccum = 3e8

global filename1
global filename2
global filename3

def openfiles():

    filename1 = open("file1.txt", "w")
    filename2 = open("file2.txt", "w")
    filename3 = open("file3.txt", "w")

def latcalc(filename,target_name,vf):


    target_name = 0

    for length in range(min_length, max_length):
            if length < 2:
                    target_name += (length/(vf * c_vaccum))
            elif length == 2:
                    target_name += delay
            else:
                    target_name = target_name

            myline="%s\t%s\n" % (length, target_name)
            filename.write(myline)


openfiles()
latcalc(filename1,lat40,0.4)
latcalc(filename2,lat80,0.8)
latcalc(filename3,lat100,1)
3
  • 2
    Why not opening the file in latcalc , and remove openfiles()? You should generally avoid using global. Commented Nov 25, 2015 at 14:15
  • first you aren't passing file name they are file handles - the object that you opened, the name is the string like 'file1.txt' Commented Nov 25, 2015 at 14:16
  • Also, is lat40 a variable? It doesn't seem to be defined. Commented Nov 25, 2015 at 14:18

4 Answers 4

2

I would create a little class (give it a useful name) to encapsulate your data. If your files grow you only have to change your create_lats

min_length = 1
max_length = 30

# delays
delay = 100

# Speed of light
c_vaccum = 3e8

#Little class to keep our data in one place 
class Lat:
    def __init__(self, filename, factor):
        self.filename = filename
        self.factor = factor
        self.file = open(filename, "w") #let the class open the file


#now our function needs only one parameter, neat!
def latcalc(lat):
    target_name = 0

    for length in range(min_length, max_length):
        if length < 2:
            target_name += (length / (lat.factor * c_vaccum)) #acces the class variable
        elif length == 2:
            target_name += delay
        else:
            target_name = target_name

        myline = "%s\t%s\n" % (length, target_name)
        lat.file.write(myline)


def create_lats():
    lats = []
    lats.append(Lat("file1.txt", 0.4))
    lats.append(Lat("file2.txt", 0.8))
    lats.append(Lat("file3.txt", 1))
    return lats


#loop over your lats created in create_lats
for lat in create_lats():
    latcalc(lat)
    lat.file.close() #close the file
Sign up to request clarification or add additional context in comments.

3 Comments

One question, does the file close cleanly once the objects are deleted ?
Not currently, I updated the loop. I think it is not the most beautiful close but it works. You could add functions open_file and close_file to your class and therefore open and close them as you wish
Thanks I shall look into it.
1

try something like this (notice the globals are gone):

def openfiles(namelist):
    ret = []
    for name in filelist:
        fi = open(name, 'w')
        ret.append(fi)
    return ret

filelist = ['file1.txt', 'file2.txt', 'file3.txt']
handles = openfiles(filelist)
for handle in handles:
    <do what ever you want>

handles will be a list of file handles corresponding to the filelist of names

note the file handle is what you pass around to do reads & writes with

also the opens could be done in the call to latcalc, since you would be doing one file per call apparently

1 Comment

Also note that all handles should be closed.
0

As some comments point out, you don't need global variables and you should close your filehandler objects after you finished writing to them which is most conveniently done with 'with' (closing is done for you, even in case of an unexpected exception):

#!/usr/bin/python

min_length = 1
max_length = 3
delay = 100
c_vaccum = 3e8

def latcalc(filename, vf):
    target_name = 0
    for length in range(min_length, max_length):
        if length < 2:
            target_name += (length/(vf * c_vaccum))
        elif length == 2:
            target_name += delay
    myline="%s\t%d\n" % (length, target_name)

    with open(filename, "w") as f:
        f.write(myline)
    return target_name

latcalc(filename1,lat40,0.4)
latcalc(filename2,lat80,0.8)
latcalc(filename3,lat100,1)

The way you treat the parameter target_name, I assume, you are used to C-type pointers which do not exist in that form in Python. The parameter is pointless here if you set it to a new value in the first line of latcalc(). Also, you seem to treat target_name as a string when it is an int:

myline="%s\t%s\n" % (length, target_name)

If you need target_name after the method has finished, you would have to return it.

Comments

-1

1) open() gives you a filehandler, and not a filename 2) Use a "with" statement for opening a file, to avoid "forgetting" closing the file when finished.

#!/usr/bin/python

# include the constants
min_length = 1
max_length = 30


# delays
delay = 100

# Speed of light 
c_vaccum = 3e8


def latcalc(filename, target_name, vf):

    with open(filename, "w") as openedFile:
        target_name = 0
        for length in range(min_length, max_length):
                if length < 2:
                        target_name += (length/(vf * c_vaccum))
                elif length == 2:
                        target_name += delay
                else:
                        target_name = target_name

                myline="%s\t%s\n" % (length, target_name)
                openedFile.write(myline)


latcalc("file1.txt", "lat40", 0.4)
latcalc("file2.txt", "lat80", 0.8)
latcalc("file3.txt", "lat100", 1)

3 Comments

Your point 1 is a little misleading. The variable name is what the OP made confusing but they used the file handler correctly (though not in the safest way).
Also, I am not sure what you want to do with "target_name", but the input parameter "target_name" is always discarded, and the output file keeps the same value on column 2 starting from second line.
point taken. the target name was really unnecessary. I shall remove it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.