【问题标题】:Python file-reader will not run in IDLE but works fine in terminal?Python 文件阅读器不会在 IDLE 中运行,但在终端中可以正常工作?
【发布时间】:2018-03-06 03:46:27
【问题描述】:

所以我为课堂创建了这个实验作业。看起来不错,只是它根本没有空闲运行。空闲打开,然后立即关闭。它在 powershell 和我使用的 IDE 中运行良好,但对于我的教授根本无法运行。

程序只是打开 randomNumbers.txt 然后列出里面的值。在此之前,我的任何程序都没有问题,而这似乎是最简单的。我忽略了一个简单的错误吗?除此之外,如果您对我可以用来优化此代码的方法有任何建议,我喜欢这些建议,我已经使用 python 2 个月了。

对不起,如果这篇文章有点长,真的很困惑。


import time, sys

def main():

     global file

     file = open("randomNumber.txt","r")

     prepArray()

     print("\n-----------\n# | Value\n-----------")

     printArray()
     file.close()

     closeInput = input("\nPress ENTER to exit")
     print("Closing...")

def prepArray():

     global numberSplit
     global file

     openFile = input("Open randomNumber.txt (Y/N): ")
     print("\n")

     if openFile.lower() == "y":

         try:
             f = open("randomNumber.txt","r")
         except IOError:
             print("Error opening file: Did you run the generator first?")
             main()

     elif openFile.lower() == "n":
         sys.exit()

     else:
         print("\nInvalid input, enter either (Y for yes, N for no)\n")
         main()     

     numberSplit = file.readline()
     numberSplit = numberSplit.split(",")
     numberSplit = numberSplit[:-1]  

def printArray():

     global numberSplit

     lineCount = 1
     totalCount = 0

     for item in numberSplit:
         print(lineCount,"-",item)
         lineCount += 1
         totalCount += float(item)

     print("\nTotal:",round((totalCount),2))
      main()

randomNumbers.txt 只包含

119.18,470.54,159.89,360.56,47.15,489.77,242.54,

【问题讨论】:

  • 可能当前目录与 IDLE 不同。
  • 要跟进@Jean-FrançoisFabre 的回复,或许可以选择使用绝对路径。

标签: python


【解决方案1】:

我正在测试您的代码并且它的工作正常!我确定你的问题是你没有 randomNumbers.txt 在同一个文件夹中,请尝试将你的 txt 文件放在你的脚本所在的同一个文件夹中,它会起作用的! ;-)

【讨论】:

  • txt 文件、文本文件生成器和文本文件阅读器都在同一个文件夹中。这就是令人困惑的事情。它应该可以工作。
  • 我看不到你的文件夹目录,但是当你的代码说 randomNumber.txt(没有's'的注释)时,我看到你调用你的文件 randomNumbers.txt(如果它相同)可能是问题在您的目录中。
  • @MilesNocte 在 IDLE 中,执行:import osprint(os.getcwd())。如果您从 GUI 启动 IDLE,它可能在与您的其余文件不同的路径中查找。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多