2013-03-26 348 views
0

我想知道是否有人可以用下面的Python 3代码来帮助我。出于某种原因,它没有做我认为应该做的事情,我不明白为什么。从Python中读取文件

with open("ModuleShow.txt", "w+", encoding='utf-8') as ModuleShowFile: 
      if ModulesLeft == 0: 
       ModuleLoaded = CommandLine[2] 
       print(ModuleLoaded) 
      else: 
       ModuleLoaded = ModuleToLoad[0] 
       ModuleToLoad.pop(0) 
       ModulesLeft = ModulesLeft - 1 
       #   ModuleFile.write("\n" + ModuleLoaded)              
       #   CommandsFile.write("module show" + ModuleLoaded)           
      output = subprocess.Popen(["bash", "-ci", "module show " + ModuleLoaded], stderr=ModuleShowFile) 

#   with open("ModuleShow.txt", "r", encoding='utf-8') as ModuleShowFile:           

      print(ModuleShowFile.read()) 
      for ModuleFileLine in ModuleShowFile: 
       FileLine = ModuleFileLine.split(" ") 

       print(FileLine[0]) 
       if FileLine[0] == "prepend-path": 
        print(FileLine[0]) 
        if FileLine[1] == "PATH": 
         ModulePathFile.write(FileLine[2] + " " + ModuleLoaded + "\n") 
        elif FileLine[0] == "module": 
         ModuleToLoad.append(FileLine[2]) 
         ModulesLeft = ModulesLeft + 1 

所以我在做什么在上面的代码信息写入名为ModuleShow.txt文件,然后分析这些信息,并写入该分析信息到一个名为ModulePath.txt文件,我打开ModulePath.txt之前,但我没有包括那部分代码,因为我相信它与我所遇到的问题无关。所以基本上,当我运行我的脚本时,内容被写入到文件中,但是当我读取内容时我什么都没有得到。例如,我尝试使用“print(ModuleShowFile.read())”,但没有打印出文件是否与内部的内容一起创建。我尝试了两个“打开()”行,一个用于写作,另一个用于阅读,但它仍然没有解决问题。希望这是简单的,我为这篇长文章道歉。我将不胜感激任何帮助。谢谢。

+0

当你尝试过使用第二'的open()',一个用于写,另一个用于读,你关闭了第一个句柄/离开了第一个'open()'上下文句柄的范围吗?换句话说,第二个'open()'是否与第一个相同或更少? – jedwards 2013-03-26 16:59:06

+0

第二个open()的缩进量与第一个open()的缩进量相同。 – user1878012 2013-03-26 17:02:19

回答

0

你甚至需要写文件ModuleShow.txt吗?或者你可以只将条目保存在列表中?

如果你真的需要再次读取他们回来,先关闭文件,像这样:

with open("ModuleShow.txt", "w+", encoding='utf-8') as ModuleShowFile: 
    # ... whatever (I'm assuming you're writing to the file here) 

# now the file is closed 
with open("ModuleShow.txt", "r", encoding='utf-8') as ModuleShowFile: 
    for ModuleFileLine in ModuleShowFile: 
     # ... now you can read each line 
+0

我已经尝试过,因为某些原因,它不起作用。我一直在搞这个,因为某些原因,当我做了以下操作时,我可以得到输出: 'with open(“ModuleShow.txt”,“w +”,encoding ='utf-8')as ModuleShowFile:' '#...写入文件的代码' 'output.communicate()#这是我从原始帖子中用' 'open(“ModuleShow.txt”,“r”,编码添加的唯一一行='utf-8')as ModuleShowFile:' ' print(ModuleShowFile.read())' '#原始帖子代码' – user1878012 2013-03-26 17:22:24

+0

如果我的评论很难理解,我可以编辑我的原始帖子码。我所做的是取消注释第二个“open”行,并在此之前添加'output.communicate()'行。任何想法为什么我可以在使用'output.communicate()'后读取文件? – user1878012 2013-03-26 17:29:49

+0

对不起,我错过了与子进程通信的一点。我猜这个子过程还没有完成,或者没有将其输出刷新到文件中。显然,wait()或者communic()可以确保它已经完成,但这对我来说是未知的领域。 – Penfold 2013-03-27 12:36:22