CSV转XLSX时遇AttributeError: pandas无read_csv属性问题求助
解决Pandas报错:
AttributeError: module 'pandas' has no attribute 'read_csv' 问题描述
在WinSCP中,CSV文件路径为/alb/alb_dev/alba/alb_dev/Fls/albb/at/conv,运行Python代码将其转换为XLSX文件时出现上述错误,执行的代码如下:
import os os.chdir('/alb/alb_dev/alba/alb_dev/Fls/albb/at/conv') import pandas as pd # The read_csv is reading the csv file into Dataframe df = pd.read_csv("./samplefile.csv") # then to_excel method converting the .csv file to .xlsx file. df.to_excel("samplefile.xlsx", sheet_name="Testing", index=False`
已尝试pip install pandas、pip-autoremove pandas -y、pip install pip-autoremove及重命名CSV文件,均未解决问题。
解决方案
1. 修复代码语法错误
最后一行代码末尾的反引号未闭合,属于语法错误,修正后代码如下:
df.to_excel("samplefile.xlsx", sheet_name="Testing", index=False)
2. 排查本地同名文件干扰
- 检查当前脚本所在目录是否存在名为
pandas.py的文件,若有则立即重命名或删除(该文件会干扰官方pandas库的正常导入)。 - 同时检查目录内是否有
pandas.pyc缓存文件,一并删除。
3. 确认Pandas安装与环境匹配
- 运行以下命令验证当前Python环境的pandas是否正常:
如果提示找不到pandas,说明当前使用的Python环境未安装该库,需对应环境执行安装:python -c "import pandas; print(pandas.__version__)"# Python3环境用pip3 pip3 install pandas # 若使用虚拟环境,先激活虚拟环境再执行安装命令
4. 调整库导入顺序
避免在切换目录后导入pandas,调整代码顺序为先导入库,再切换目录:
import pandas as pd import os os.chdir('/alb/alb_dev/alba/alb_dev/Fls/albb/at/conv') df = pd.read_csv("./samplefile.csv") df.to_excel("samplefile.xlsx", sheet_name="Testing", index=False)
5. 安装to_excel依赖库
使用to_excel方法需要依赖openpyxl库,若未安装会触发额外错误,执行安装:
pip install openpyxl
内容的提问来源于stack exchange,提问作者Sherin Shaziya
相关产品推荐
相关产品推荐

