【问题标题】:Getting Identifier expected in Pycharm when importing a file导入文件时在 Pycharm 中获取预期的标识符
【发布时间】:2021-03-03 02:26:00
【问题描述】:

我正在尝试从其他文件夹中的其他文件导入信息,但我的程序一直显示“需要标识符”

from builtins import object
import os
import pygame
import random

pygame.init()
os.environ['SDL_VIDEO_WINDOW_POS'] = '0, 30'
from folder1 import 'splash text.txt*'
splashget = open('splash text.txt', 'r')
splashget = splashget.readlines()
splashtextchoice = random.choice(splashget)
screenwidth = 1920
screenheight = 1080
win = pygame.display.set_mode((screenwidth, screenheight))

我的文件结构是这样组织的:

Project
|
-----App
|
-----Folder1
       |
       -------splash text.txt

错误出现在 from folder1 import 'splash text.txt'* 在第一个撇号上。这个文本文件上有几个小短语,每个小短语都换行。有什么帮助解决这个问题吗?

【问题讨论】:

    标签: python import python-import


    【解决方案1】:

    import 语句用于使.py 文件的类、方法和/或函数在不同的.py 文件中可供您使用。您不能导入.txt 文件,您可以使用open() 函数(使用with open()f = open(...))打开它们。您已经在执行后者,但您还必须考虑包含您要访问的文件的目录(即Folder1),所以我建议您这样做:

    # with the with context manager
    
    with open('Folder1/splash text.txt', 'r') as splashget:
        # do code stuff here
    
    # with the f = open(...) method
    
    splashget = open('Folder1/splash text.txt', 'r')
    # do code stuff here
    splashget.close()
    

    其中任何一个都会在您所在的文件中打开splash text.txt。 (请参阅下面的注释,了解为什么在前面添加 Folder1/ 可以让我们打开文件。)

    注意:'Folder1/splash text.txt' 是一个相对文件路径(如如何从您所在的文件中获取您想要的文件/目录),Python 将执行必要的逻辑将其转换为绝对文件路径(如何从驱动器顶部到您想要的文件/目录,例如从C:Folder1)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-06
      • 1970-01-01
      相关资源
      最近更新 更多