Python- os.chdir 在执行时考虑一个打开的 excel 文件实例

Python- os.chdir takes an open excel file instance into account while execution

我的文件夹中有一些 excel 个文件。我使用下面的代码读取那些 excel 文件并将它们放入列表中,以便我可以将该列表传递到循环中以从所有这些文件中获取特定数据。

我的问题是 - 如果我从该文件夹打开一个 excel 文件并且 运行 打开 script.The excel 文件实例是在该文件夹和脚本中创建的现在将该临时实例作为 .xlsx 文件并将其返回到列表中并将其传递到最终失败的循环 -"No such directory" 我找到了一种通过添加“-1”来避免失败的方法来自列表长度 loop.But 这无效。

请提出 os.chdir

的替代方案
import pandas as pd
import glob
import os

os.chdir(r'\servername/Files_to_Read')
files = [i for i in glob.glob('*.{}'.format('xlsx'))]
print(files)

s = 0
while(len(files) > s):
    print(files[s])
    df_getvalues = pd.read_excel(files[s], sheet_name="LISTS", header=None)
    dfindx = (df_getvalues.index)
    print("This is the index of the file - " +str(dfindx))
    print(df_getvalues.iloc[dfindx,0])
    s = s + 1

错误:-

FileNotFoundError: [Errno 2] 没有那个文件或目录: 'C:\Users$name_of_file.xlsx'

错误指出它正在 C 盘中搜索文件,但 excel 个文件的实际文件夹在 H 盘中。

注意 - 我使用 Windows 10,Excel 2016,python 3.7

这个问题似乎是间歇性的,在我重新启动后再也没有发生过,我的 VM 迁移也有一些问题,我的配置文件是手动配置的,所以我不知道各种原因中有哪些对我有帮助摆脱这个问题。

此外,我现在不使用 OS.Chdir。这次我使用路径和列表目录,因为我在某处看到不推荐使用 chdir。

list_dirctry_content = os.listdir(src)

for xlfile in list_dirctry_content:
    str_name_file = os.path.join(src, xlfile)
    if(str_name_file.endswith('.xlsx')):
        final_driving_list.append(str_name_file.strip(src))