我使用 venv (Python 3.xx) 创建了一个虚拟环境。
那里,我只安装了几个包:
我有一个 Python 脚本,它读取给定目录中的文件并使用 Pandas 操作它们的数据:
import pandas as pd
import os
path = os.getcwd()+'\Ph3_Charts'+'\\'
print(path)
from os import listdir
from os.path import isfile, join
days_range = [f for f in listdir(path) if isfile(join(path, f))]
dataframes = []
count = 0
for i in days_range:
try:
print(i,count)
dataframes.append(pd.read_excel(path+i, sheet_name = "Issues Jira", index_col=0))
count += 1
except:
pass
问题似乎出在变量 path
上,因为程序在尝试从每个列出的文件中附加一些数据帧时会中断。
但是,上面红色标记的段落显示的路径很好......最奇怪的是,当我在本地运行这个程序时,迭代工作正常。
请猜猜为什么会发生这种情况?
答案 0 :(得分:1)
问题的根源在于您强制脚本将反斜杠 \
用作 the path separator。您的远程系统使用 Linux,而您在本地使用 Windows。与 Windows、Linux 和 macOS 系统 prefer to use the forward slash 不同,用于分隔系统路径中的目录。这就是差异的原因。
下面是一个正确的 platform independent 实现,可以避免这种不必要的特殊性:
import pandas as pd
import os
from os import listdir
from os.path import isfile, join
# Get CWD
CWD = os.getcwd()
# Join CWD with `Ph3_Charts` folder
PH3_CHART_PATH = os.path.join(CWD, 'Ph3_Charts')
print("PH3 chart path: '"+PH3_CHART_PATH+"'")
days_range = [f for f in listdir(PH3_CHART_PATH) if isfile(join(PH3_CHART_PATH, f))]
dataframes = []
count = 0
for i in days_range:
try:
print(i,count)
dataframes.append(pd.read_excel(PH3_CHART_PATH+i, sheet_name = "Issues Jira", index_col=0))
count += 1
except Exception as e: # catch *all* exceptions
print(e) # print it out
无论是否使用您讨论的 venv
功能,此解决方案都适用。请参阅文件 diff here(您的版本与上述代码之间的差异比较)。