【问题标题】:Bash script creates separate files with same contentBash 脚本创建具有相同内容的单独文件
【发布时间】:2018-12-10 14:49:12
【问题描述】:

我有 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 的内容。这是一个问题吗,即使我说要循环遍历脚本中这些文件夹中的文件,我还是以某种方式进行了硬编码?

【问题讨论】:

  • @sjaustirni 希望这可以澄清,涉及很多脚本,但这是我的问题源于
  • I cannot cd into a folder or use a for loop extension line in my bash script,好吧,你总是可以find。为什么我在您的帖子和标签中看到 bash,而我在您的源代码中看到了 python。是python还是bash?
  • @KamilCuk 我只是在我的 bash 脚本中以这种方式运行 python 脚本。但我实际上设法通过将我的计算存储在一个列表中然后在我的 test.py 脚本中的 for 循环中迭代它们来修复它。谢谢!

标签: bash


【解决方案1】:

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

   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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-10
    • 2016-02-25
    • 2016-07-31
    • 1970-01-01
    相关资源
    最近更新 更多