首页 > 解决方案 > 从终端窗口运行 python

问题描述

我正在测试从命令提示符运行 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 代码。

我希望有人知道

标签: pythonpandasterminalcommand-prompt

解决方案


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:您正在运行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', ';') 

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


推荐阅读