python - 从终端窗口运行 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 代码。
我希望有人知道
解决方案
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
以查看您所在的目录。
推荐阅读
- flutter - 为什么 Bloc 不在上下文中?
- sql-server - Cloud SQL(SQL Server 2017)与SSMS连接,可以吗?
- azure-active-directory - 用户 JWT 与 client_credentials JWT 的不同权限
- ios - App Crash (SIGABRT) 仅在 AppStore Review 中,不在 Sim 或我的硬件中
- python - 如何将线性字符串变成特里?
- javascript - 如何在javascript中清空数组数组?
- java - 为什么这不会从我的 java 列表中删除重复项?
- pandas - 使用 Datetime 转换 pandas 数据框列(字符串)
- angular - 无法投影
s 到自定义组件中 - node.js - 显示特定帖子 ID 的聊天消息