运行 python 从终端 windows

running python from the terminal windows

我正在从命令提示符测试 运行 一个 python 文件。 运行 像 print('Hello world') 这样的简单代码正在运行。但是如果我 运行 下面的代码我会得到一个错误。

代码:

import pandas as pd

df = pd.read_excel('Test.xlsx')

df.to_csv('_TEST.csv', ';') 

错误:

FileNotFoundError: [Errno 2] No such file or directory: 'Test.xlsx'

文件位于正确的目录中。因为该代码适用于 IDE、Visual studio 代码。

希望有人知道

如果文件在正确的目录中,则可能是您执行脚本的目录有问题。将命令提示符中的目录更改为 Visual Studio 代码中终端中显示的同一目录。

有两种情况Python无法识别您的文件: 假设您的脚本名为 hello.py

案例 1: 您正在 运行 宁 python hello.py 并且文件在其他地方,例如 another_folder/Test.xlsx 那么:

import pandas as pd

df = pd.read_excel('another_folder/Test.xlsx')

df.to_csv('_TEST.csv', ';') 

案例 2: 你正在 运行ning python another_folder/hello.py 并且文件也在同一个文件夹中,说 another_folder/Test.xlsx 然后它也是:

import pandas as pd

df = pd.read_excel('another_folder/Test.xlsx')

df.to_csv('_TEST.csv', ';') 

原因是你必须写你的文件相对于 current working directory 的路径, 而不是 相对于 python 文件。 提示: 运行 pwd 在命令行中查看您所在的目录。