导入找不到相同文件夹的文件

2024-03-28 18:23:02 发布

您现在位置:Python中文网/ 问答频道 /正文

导入找不到相同的文件。现在,我在文件夹a中有a、b、c文件。 文件a读取b&c一个。第一个,我在一个类似

import b
import c
   ・
  ・
  ・   
x = b_method()
y = c_method()

但是,错误是“没有名为b的模块”

from A import b
from A import c
   ・
     ・
     ・   
x = b_method()
y = c_method()

但是,当我运行这个文件时,终端说

ImportError: No module named 'A'     

那么,如何读取文件a中的文件b&c? 我怎样才能解决这个问题? 我补充道

import os
import sys
file_dir = os.path.dirname(__file__)
sys.path.append(file_dir) 

但它不起作用。你知道吗

我的项目结构是

test   (parent app)
|--- A
      |
      ---- a
      ---- b
      ---- c

回溯说

Traceback (most recent call last):
  File "a.py", line 10, in <module>
    from A import b
ImportError: No module named 'A'

我写import b的时候, 回溯说

Traceback (most recent call last):
  File "a.py", line 58, in <module>
    xxx = b.parse(user, id)
NameError: name 'b' is not defined

整个a.p

import sys
import os
import b
import c


LOG_FILENAME = 'excel.log'
file_dir = os.path.dirname(__file__)
sys.path.append(file_dir)

logger = logging.getLogger()
logger.setLevel(logging.DEBUG)

handler = logging.handlers.RotatingFileHandler(
    LOG_FILENAME, maxBytes=2000000, backupCount=5, encoding='utf-8')
handler.setFormatter(
    logging.Formatter('%(asctime)s %(levelname)s %(name)s %(message)s'))
handler.setLevel(logging.DEBUG)
logger.addHandler(handler)

console = logging.StreamHandler()
console.setLevel(logging.INFO)
logger.addHandler(console)

# READ
def read_config():
    f = codecs.open('config.json', 'r', 'utf-8')
    text = f.read()
    config = json.loads(text)
    return config

try:
    logger.debug('start.')
    logger.info("--------------------------------")
    logger.info("Excelファイル読込処理を開始します。")
    logger.info("--------------------------------")
    config = read_config()
    output_dir = config['output_dir']

    logger.info("クライアントのデータを読み込みます。")
    book_name = config['client']['file_name']
    regions = config['client']['regions']
    #clientsが空だと、jsonがoutputされない
    xxx = b.parse(user, id)
    yyy = c.parse(name,mail)
    logger.info("--------------------------------")

# ERROR
except:
    logger.exception('exception occurred.')
    print(input("error"))
    sys.exit(-1)

logger.debug('end.')
print(input("finish"))
sys.exit(0)

Tags: 文件pathnameimportinfoconfigoslogging
2条回答

在目录和Python中创建一个空文件__init__.py,可以识别允许从中导入的目录。然后你用

import b
import c

确保两件事: 您尝试导入的文件与您正在使用的文件位于同一文件夹/目录中 这些文件可以与python一起使用(应该使用.py文件)

确定后,在空闲时尝试以下操作:

>>> import b
>>> import c
>>> c
>>> b

完成之后,python应该会给您一条消息,告诉您关于特定模块的信息

相关问题 更多 >