简体   繁体   English

(Python)ImportError:无法导入名称

[英](Python)ImportError: cannot import name

I have a variable named nombre in file 1. 我在文件1中有一个名为nombre的变量。

print("\nREGISTRO DE USUARIO\n")
nombre=input("Nombre completo: ")
tel=input("Numero telefonico: ")
direc=input("Direccion: ")
print("\t\tUSUARIO REGISTRADO")
input()

Now, I want to import the variable nombre to file 2 现在,我想将变量nombre导入文件2

    from usuario import nombre
    numerolista=[]
    numerolista.append(nombre)
    print (numerolista)

But it returns the error 但它返回错误

ImportError: cannot import name 'nombre'. ImportError:无法导入名称“ nombre”。

Please Check weather the files were there in the same folder. 请检查天气文件在同一文件夹中。 in case they were there in different folder try adding the folder path which is having the first file in your import section. 如果它们在不同的文件夹中,请尝试在导入部分添加第一个文件所在的文件夹路径。 You can add the path in the following way. 您可以通过以下方式添加路径。

    from sys import path
    path += [<first_file_path>]

and remember while adding path just specify the folder path, for instance if the first file is in D:\\Data\\Python\\Work\\file1.py 并记住在添加路径时只需指定文件夹路径即可,例如,如果第一个文件位于D:\\ Data \\ Python \\ Work \\ file1.py中

specify the path as 将路径指定为

    path += ['D:\\Data\\Python\\Work']

if you have the second file also in the same hierarchy you can specify the path as below. 如果第二个文件也位于相同的层次结构中,则可以指定以下路径。 Lets Say your second file is in the following path 假设您的第二个文件位于以下路径中

    D:\Data\Python\files\file2.py 

In thi scase you can specify the path as 在这种情况下,您可以将路径指定为

    path += ['..\\Work']

Dont forget to add these 2 lines before your from usuario import nombre . 不要忘记在从usuario import nombre之前添加这两行。 So that first the path will be added the library path so that your import statement will work. 因此,首先将路径添加到库路径,以便您的import语句将起作用。

Hope this will help you. 希望这会帮助你。 Thanks 谢谢

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

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