简体   繁体   English

在 Python 中从另一个文件导入列表

[英]Importing List from antoher File in Python

I have 2 files in the same directory:我在同一目录中有2个文件:

func.py:函数.py:

import openpyxl

def openText():
 wb = openpyxl.load_workbook('/Users/*****/*****/****/****/*****/main/Sentences.xlsx')
 sheet = wb["Sheet1"]
 i = 2
 Text = []
 Row = sheet[f'A{i}'].value

 while Row != None:
       Text.append(Row)
       i += 1
       Row = sheet[f'A{i}'].value
 return Text

main.py:主要.py:

from func import Text
from func import openText

openText()

print[Text]

The Text list should be imported, but I get this error:应该导入文本列表,但我收到此错误:

cannot import name 'Text' from 'func'

Declare Text globally in func.py file.func.py文件中全局声明Text Inside the method add this statement global Text .在方法内部添加此语句global Text

import openpyxl
Text = []
def openText():
 wb = openpyxl.load_workbook('/Users/*****/*****/****/****/*****/main/Sentences.xlsx')
 sheet = wb["Sheet1"]
 i = 2
 Row = sheet[f'A{i}'].value
 global Text
 while Row != None:
       Text.append(Row)
       i += 1
       Row = sheet[f'A{i}'].value
 return Text

In the main.py file, call openText and you'll get the same Text from the func.py file:main.py文件中,调用openText ,您将从func.py文件中获得相同的Text

from func import Text
from func import openText

x=openText()

print(x)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM