【问题标题】:When import a python file into another (in a subdirectory) it stops finding the csv in the same directory将 python 文件导入另一个(在子目录中)时,它会停止在同一目录中找到 csv
【发布时间】:2021-11-06 21:54:25
【问题描述】:

我正在尝试将清理文件导入管理器文件中,如下所示:

import sys
import os

sys.path.append(os.path.dirname(os.path.abspath("cleaning.py")))
from cleaning import df_invoices_full

主文件夹包含文件清理、事务列表和一个名为“apps”的子文件夹,其中包含管理器文件:

还要注意,清理文件读取的是交易listing.csv文件。

我在运行时遇到的问题是:

FileNotFoundError: [Errno 2] No such file or directory: 'Transaction Listing.csv'

并且“Transaction Listings.csv”通过清理正确加载,但在清理导入管理器时没有。

感谢您的帮助。

【问题讨论】:

  • 请将相关代码的minimal reproducible example发到cleaning.py
  • cleaning.py 独立运行良好,仅供参考
  • df_invoices_full = pd.read_csv("Transaction Listing.csv", encoding='latin-1')

标签: python path operating-system sys


【解决方案1】:
#-- cleaning.py --#

import os
import pandas as pd

csv_filename = "Transaction Listings.csv"
folder = os.path.dirname(os.path.abspath(__file__))
path_to_csv = os.path.join(folder, csv_filename)

df_invoices_full = pd.read_csv(path_to_csv, encoding="latin-1") 

cleaning.py 中使用此代码,而不是您当前的代码。

发生的情况是,当cleaning.py 导入apps/managers.py 时,它在apps 文件夹中运行,而不是在 CSV 文件所在的基本文件夹中运行。通过给出绝对路径,pd.read_csv() 将在正确的位置查找文件——cleaning.py 实际所在的目录。请参阅what does the __file__ variable mean/do?

【讨论】:

  • 是的,这确实是问题所在,很高兴知道它是如何工作的,非常感谢马特,你真棒!
猜你喜欢
  • 2023-02-02
  • 2021-09-23
  • 2021-08-17
  • 2023-03-20
  • 1970-01-01
  • 2021-02-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多