【问题标题】:Python- os.chdir takes an open excel file instance into account while executionPython- os.chdir 在执行时会考虑一个打开的 excel 文件实例
【发布时间】:2019-11-14 18:26:13
【问题描述】:

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

我的问题是 - 如果我从该文件夹打开一个 excel 文件并运行脚本。打开的 excel 文件实例是在文件夹中创建的,脚本现在将该临时实例作为 .xlsx 文件并将其返回到列表中并将其传递给最终失败的循环 - “没有这样的目录”我找到了一种避免失败的方法,方法是在列表长度中添加一个“-1”到循环。但这不是有效的。

请为 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

【问题讨论】:

    标签: python excel pandas python-3.7 glob


    【解决方案1】:

    这个问题似乎非常间歇性,并且在我重新启动后再也没有发生过,我的 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))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-08-24
      • 1970-01-01
      • 2014-09-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多