首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >导入sys,sys.path.insert()不工作

导入sys,sys.path.insert()不工作
EN

Stack Overflow用户
提问于 2020-04-15 10:16:11
回答 1查看 1.5K关注 0票数 1

我正在尝试导入一个名为cards.py的.py文件,该文件简单地定义了两类对象。

我已经研究了多个线程,最常见的方法是:

代码语言:javascript
复制
import sys
# insert at 1, 0 is the script path (or '' in REPL)
sys.path.insert(1, '‪C:/Users/username/Downloads/')
import cards

我一直收到错误:

代码语言:javascript
复制
ModuleNotFoundError: No module named 'cards'

但是这个文件很明显就在那个目录里。我试过其他的选择,比如

代码语言:javascript
复制
import sys
# insert at 1, 0 is the script path (or '' in REPL)
sys.path.insert(1, '‪‪C:\\Users\\username\\Downloads')
import cards
代码语言:javascript
复制
import sys
# insert at 1, 0 is the script path (or '' in REPL)
sys.path.insert(1, '‪‪C:\\Users\\username\\Downloads\\')
import cards

代码语言:javascript
复制
import importlib
importlib.import_module("‪C:\\Users\\username\\Downloads\\cards.py")
代码语言:javascript
复制
import importlib
importlib.import_module("‪C:\\Users\\username\\Downloads\\cards")
代码语言:javascript
复制
import importlib
importlib.import_module("‪C:\\Users\\username\\Downloads\\")

如果有任何帮助,我们将不胜感激,如果有帮助,下面是card.py文件中的代码:

代码语言:javascript
复制
import random

class Card( object ):
    """ Model a playing card. """

    # Rank is an int (1-13), where aces are 1 and kings are 13.
    # Suit is an int (1-4), where clubs are 1 and spades are 4.
    # Value is an int (1-10), where aces are 1 and face cards are 10.

    # List to map int rank to printable character (index 0 used for no rank)
    rank_list = ['x','A','2','3','4','5','6','7','8','9','10','J','Q','K']

    # List to map int suit to printable character (index 0 used for no suit)
    suit_list = ['x','\u2663','\u2666','\u2665','\u2660']

    def __init__( self, rank=0, suit=0 ):
        """ Initialize card to specified rank (1-13) and suit (1-4). """
        self.__rank = 0
        self.__suit = 0
        # Verify that rank and suit are ints and that they are within
        # range (1-13 and 1-4), then update instance variables if valid.
        if type(rank) == int and type(suit) == int:
            if rank in range(1,14) and suit in range(1,5):
                self.__rank = rank
                self.__suit = suit

    def rank( self ):
        """ Return card's rank (1-13). """
        return self.__rank

    def value( self ):
        """ Return card's value (1 for aces, 2-9, 10 for face cards). """
        # Use ternary expression to determine value.
        return self.__rank if self.__rank < 10 else 10

    def suit( self ):
        """ Return card's suit (1-4). """
        return self.__suit

    def __str__( self ):
        """ Convert card into a string (usually for printing). """
        # Use rank to index into rank_list; use suit to index into suit_list.
        return "{}{}".format( (self.rank_list)[self.__rank], \
                              (self.suit_list)[self.__suit] )
        # version to print Card calls for developing tests
        #return "cards.Card({},{})".format( self.__rank, self.__suit )

    def __repr__( self ):
        """ Convert card into a string for use in the shell. """
        return self.__str__()

    def __eq__( self, other ):
        """ Return True, if Cards of equal rank and suit; False, otherwise. """
        if not isinstance(other, Card):
            return False

        return self.rank() == other.rank() and self.suit() == other.suit()

class Deck( object ):
    """ Model a deck of 52 playing cards. """

    # Implement the deck as a list of cards.  The last card in the list is
    # defined to be at the top of the deck.

    def __init__( self ):
        """ Initialize deck--Ace of clubs on bottom, King of spades on top. """
        self.__deck = [Card(r,s) for s in range(1,5) for r in range(1,14)]

    def shuffle( self ):
        """ Shuffle deck using shuffle method in random module. """
        random.shuffle(self.__deck)

    def deal( self ):
        """ Return top card from deck (return None if deck empty). """
        # Use ternary expression to guard against empty deck.
        return self.__deck.pop() if len(self.__deck) else None

    def is_empty( self ):
        """ Return True if deck is empty; False, otherwise """
        return len(self.__deck) == 0

    def __len__( self ):
        """ Return number of cards remaining in deck. """
        return len(self.__deck)

    def __str__( self ):
        """ Return string representing deck (usually for printing). """
        return ", ".join([str(card) for card in self.__deck])

    def __repr__( self ):
        """ Return string representing deck (for use in shell). """
        return self.__str__()

    def display( self, cols=13 ):
        """ Column-oriented display of deck. """
        for index, card in enumerate(self.__deck):
            if index%cols == 0:
                print()
            print("{:3s} ".format(str(card)), end="" )
        print()
        print()
EN

回答 1

Stack Overflow用户

发布于 2020-04-15 10:26:30

也许可以使用append而不是insert

代码语言:javascript
复制
import sys
sys.path.append("‪C:\\Users\\username\\Downloads\\")
import cards
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61220239

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档