使用控制台启动程序时无法写入文件

问题描述 投票:1回答:2

我最近启动了Python,我想创建一个程序来读取文件中的计算,执行该程序(使用eval()函数),然后将结果写入另一个文件中。该程序必须使用控制台启动。

我已经创建了该程序,双击该程序可以很好地运行它。但是,当我使用控制台启动程序时,它不会将结果写入文件,也不会出现任何错误。我知道计算已经完成,因为结果写在控制台中。

我已经尝试过运行具有.py扩展名的程序,并使用pyinstaller将其编译为可执行文件。它们可以双击,但不能从控制台使用。

这是我用来运行程序的命令:

F:\Path\To\App\calculator.exe

C:\Path\To\Python\python.exe F:\Path\To\App\calculator.py

我用来读取,评估和编写计算的代码

input = open('calcul.txt', 'r')
output = open('result.txt', 'w')

calcul = input.read()
print(calcul)
print(eval(calcul).toString())
output.write(eval(calcul).toFileString())

input.close()
output.close()

def toString(self):
        number = str (round(self.m_number, 4))
        number_scientific = str(format(self.m_number, ".3E"))
        imprecision = str (round(self.m_imprecision, 4))
        imprecision_scientific = str(format(self.m_imprecision, ".3E"))
        relative_imprecision = str(round(self.m_relative_imprecision * 100, 2))

        return "\t  Number \t\t= " + number + " \t= " + number_scientific + "\n\t  Imprecision \t\t= " + imprecision + " \t= " + imprecision_scientific + "\n\t  Relative Imprecision \t= " + relative_imprecision + "%\n\t"

def toFileString(self):
        return str (round(self.m_number, 4)) + '\n' + str (round(self.m_imprecision, 4))

当我以管理员身份运行控制台时,我知道:

C:\WINDOWS\system32>F:\Users\Ludovic\Desktop\Apprentissage\C++\Qt\calculator\python_calculator\calculator.exe
Traceback (most recent call last):
  File "calculator.py", line 376, in <module>
    calcul = input.read()
FileNotFoundError: [Errno 2] No such file or directory: 'C:\\WINDOWS\\system32\\calcul.txt'
[26580] Failed to execute script calculator

C:\WINDOWS\system32>C:\Users\Ludovic\AppData\Local\Programs\Python\Python38\python.exe F:\Users\Ludovic\Desktop\Apprentissage\C++\Qt\calculator\python_calculator\calculator.py
Traceback (most recent call last):
  File "F:\Users\Ludovic\Desktop\Apprentissage\C++\Qt\calculator\python_calculator\calculator.py", line 373, in <module>
    input = open('calcul.txt', 'r')
FileNotFoundError: [Errno 2] No such file or directory: 'calcul.txt'
python file console
2个回答
0
投票

以管理员身份运行控制台,并在inputoutput文件中添加路径

input = open('your_path_to_file\calcul.txt', 'r')
output = open('your_path_to_file\result.txt', 'w')

或将文件放在脚本文件夹中,然后像这样调用它们

import sys
input = open(sys.path[0]+'\\calcul.txt', 'r')
output = open(sys.path[0]+'\\result.txt', 'w')

0
投票

也许您不在您希望编写示例txt文件的目录中:如果您在cmd中:MyFolder\然后通过以下命令执行python文件:python MyFolder\Python_prog\program.py.txt文件将用MyFolder\而不是MyFolder\Python_prog\写入我不确定,因为我从未尝试过python,因为我遇到过与JavaScript类似的错误

© www.soinside.com 2019 - 2024. All rights reserved.