简体   繁体   English

将文件和值作为参数传递给python中的函数

[英]passing files and values as parameter to a function in python

I am a python newbie.我是一个蟒蛇新手。 I am trying to run this simple python example.我正在尝试运行这个简单的 python 示例。 I am wish to pass files and certain values as parameter to my function latcalc().我希望将文件和某些值作为参数传递给我的函数 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)

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如果您的文件增长,您只需更改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

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 handles 将是与名称文件列表相对应的文件句柄列表

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也可以在对 latcalc 的调用中完成打开,因为显然每次调用都会执行一个文件

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):正如一些评论指出的那样,您不需要全局变量,您应该在完成写入文件后关闭文件处理程序对象,这最方便使用 'with' 完成(关闭已为您完成,即使出现意外异常) :

#!/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.你对待参数target_name 的方式,我假设,你已经习惯了 C 类型的指针,这些指针在 Python 中不以这种形式存在。 The parameter is pointless here if you set it to a new value in the first line of latcalc().如果您在 latcalc() 的第一行中将其设置为新值,则该参数在此处毫无意义。 Also, you seem to treat target_name as a string when it is an int:此外,当target_name是 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.如果在方法完成后需要 target_name,则必须返回它。

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. 1) open() 为您提供文件处理程序,而不是文件名 2) 使用“with”语句打开文件,以避免在完成时“忘记”关闭文件。

#!/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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM