首页 > 解决方案 > Bash 脚本创建具有相同内容的单独文件

问题描述

我有 3 组文件,每组文件位于不同的文件夹中,因此我无法 cd 进入文件夹或在我的 bash 脚本中使用 for 循环扩展行。我在 bash 中的最后一个脚本是这样写的:

  python test.py

在我的 test.py 脚本中:

    for file in os.listdir(/path to folder1):
        with open((/path to folder4+file+'.txt')), 'w') as w:
             w.write #according to calculations calculated earlier in test.py from folder1
             w.write #according to calculations calculated earlier in test.py from folder2
             w.write #according to calculations calculated earlier in test.py from folder3

当我浏览我的第一个 PDB 文件(输出:PDB1.txt)时,它会正确执行此操作,但是当它运行第二个文件时,我会得到 PDB2.txt,但它包含 PDB1.txt 的内容。这是一个问题吗,即使我说要循环遍历脚本中这些文件夹中的文件,我还是以某种方式进行了硬编码?

标签: bash

解决方案


解答:我没有使用返回,而是将答案附加到列表中,然后循环遍历列表中的答案

   def funtion1():
        list1 = []
        (do calculations)
        return list1()

   def main_function():   
        f1 = function1()
        for file in os.listdir(/path to folder1):
            with open((/path to folder4+file+'.txt')), 'w') as w:
                 for i in f1:
                      w.write(f1[i]) #according to calculations calculated earlier in test.py from folder1

因此,现在,当我遍历包含来自不同文件的多个计算的列表时,它不会只返回相同的计算,而是正确读取每个计算。


推荐阅读