将单个数组元素写入唯一的文件

2024-09-28 05:41:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个数组,infileoutfile

infile = ['Apple', 'Orange', 'Banana']
outfile = ['Applefile', 'Orangefile', 'Bananafile']

我在readin.txt中搜索infile数组中的每个元素,对于包含所述元素的任何一行,我会做一些事情。这就是readin.txt的样子:

Apple = 13
Celery = 2
Orange = 5
Banana = 
Grape = 4

outfile数组包含我要创建的文件的名称;每个文件对应于infile中的一个元素。infile中的第一个元素对应于outfile中的第一个元素(文件名),依此类推。你知道吗

我遇到的问题是这段代码:

for line in open("readin.txt", "r"):
    for i in infile:
        if i in line:
            sp = line.split('=')
            sp1 = str(sp[1])
            def parseline(l):
                return sp1.strip() if len(sp) > 1 and sp[1].strip() != '' else None
                for s in outfile:          
                    out = parseline(line)
                    outw = open(s, "w")
                    outw.write(str(out))
                    outw.close()

在代码的第一部分,我想在readin.txt中搜索infile(即AppleOrangeBanana)中的任何一个单词。然后,我希望代码选择出该单词出现的整行。我知道readin.txt中的任何这样的行都将包含一个等号,因此我希望代码围绕等号拆分该行,并只生成等号后面的行。你知道吗

虽然代码的最后一部分确实为outfile中的每个元素创建了单独的文件,但实际的输出总是对应于infile的最后一个元素。就好像循环中的每个后续步骤都覆盖了前面的步骤。我觉得我需要查看i的第line个元素,但我不知道如何在Python中这样做。任何帮助都会很好。你知道吗

为清晰起见进行编辑,并希望重新打开问题:

实际上,下面的代码似乎正是我想要的:

for line in open("parameters.txt", "r"):
    for i in infile:
        if i in line:
            sp = line.split('=')
            sp1 = str(sp[1]).strip() if len(sp) > 1 and sp[1].strip() != '' else None      
            print sp1

在命令行上,我得到:

13
5
None

所以这告诉我,代码的第一部分基本上是在做我希望它做的事情(虽然可能不是以最有效的方式,所以任何其他的建议都会很感激)。你知道吗

此时,我希望打印出来的所有信息都基于outfile数组写入到各个文件中。也就是说13应该被输入一个名为Applefile的文件,None应该被写入一个名为Bananafile的文件,等等。这就是我遇到的问题。我知道'outfile'应该以类似的方式编制索引,以便outfile的第一个元素对应于infile的第一个元素,但我的尝试到目前为止还没有成功。你知道吗

这是我最近的一次尝试:

for line in open("parameters.txt", "r"):
    for i in infile:
        if i in line:
            def parseline(l): 
                sp = l.split('=')
                sp1 = str(sp[1]).strip() if len(sp) > 1 and sp[1].strip() != '' else None      
                if sp1:
                    out = parseline(line)
                    outw = open(outfile[i], "w")
                    outw.write(line)
                    outw.close()

因为某种原因,在代码中提前定义parseline会否定代码的整个开头部分。你知道吗

我不是在寻找答案。我想了解发生了什么,并能够找出如何解决它。你知道吗


Tags: 文件代码intxt元素forifline
2条回答

我将把它分解为两个步骤:

def parse_params(filename):
    """Convert the parameter file into a map from filename to value."""
    out = {}
    with open(filename) as f:
        for line in f:
            word, num = map(str.strip, line.split("="))
            out[word] = num
    return out # e.g. {'Celery': '2', 'Apple': '13', 'Orange': '5'}

def process(in_, out, paramfile):
    """Write the values defined in param to the out files based on in_.""" 
    value_map = parse_params(paramfile)
    for word, filename in zip(infile, outfile):
        if word in value_map:
            with open(filename, 'w') as f: # or '"{0}.txt".format(filename)'
                f.write(value_map[word])
        else:
            print "No value found for '{0}'.".format(word)

process(infile, outfile, "parameters.txt")

您当前的代码没有什么意义:

for line in open("parameters.txt", "r"): # iterate over lines in file
    for i in infile: # iterate over words in infile list
        if i in line: # iterate over characters in the file line (why?)
            def parseline(l): # define a function
                sp = l.split('=')
                sp1 = str(sp[1]).strip() if len(sp) > 1 and sp[1].strip() != '' else None      
                if sp1:
                    out = parseline(line)
                    outw = open(outfile[i], "w")
                    outw.write(line)
                    outw.close()
# but apparently never call it (why?)

在两个循环中使用相同的循环变量名是个坏主意,您只能看到内部值:

>>> for x in range(2):
    for x in "ab":
        print x


a
b
a
b

如果您发现某个函数“需要”在某个特定位置定义,则表明您正依赖作用域来访问变量。为所需的参数定义特定的参数和返回值要好得多;这使开发和测试更加容易。你知道吗

the actual output within every single file created corresponds to the last element of infile

因为对于infile的每一个元素,您都在outfile的每一个元素上循环并写入最新的一行,所以最终所有文件都包含最后一行是有意义的。由于您的infile/outfile行对应,您可以使用主infile循环中的i索引从outfile获取您想要的标签。。比如:

for line in open("readin.txt", "r"):
    for i in infile:
        if i in line:
            sp = line.split('=')
            sp1 = str(sp[1]).strip() if len(sp) > 1 and sp[1].strip() != '' else None
            if sp1:
                out = parseline(line)
                outw = open(outfile[i], "w")
                outw.write(str(out))
                outw.close()

相关问题 更多 >

    热门问题