繁体   English   中英

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

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

我是一个蟒蛇新手。 我正在尝试运行这个简单的 python 示例。 我希望将文件和某些值作为参数传递给我的函数 latcalc()。 谁能建议我如何将我的文件和值作为参数传递。 或者有没有更好的方法/方法来做这些事情。

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

我会创建一个小类(给它一个有用的名字)来封装你的数据。 如果您的文件增长,您只需更改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

尝试这样的事情(注意全局变量不见了):

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

请注意,文件句柄是您传递的用于读取和写入的内容

也可以在对 latcalc 的调用中完成打开,因为显然每次调用都会执行一个文件

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

你对待参数target_name 的方式,我假设,你已经习惯了 C 类型的指针,这些指针在 Python 中不以这种形式存在。 如果您在 latcalc() 的第一行中将其设置为新值,则该参数在此处毫无意义。 此外,当target_name是 int 时,您似乎将其视为字符串:

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

如果在方法完成后需要 target_name,则必须返回它。

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