【问题标题】:importing string between two files在两个文件之间导入字符串
【发布时间】:2014-09-02 17:10:11
【问题描述】:

看来我不是很了解导入功能。我想以两种方式做到这一点。

文件1:

filename="tt.txt"
import file2
from file imort fileContent

文件2:

from file1 import filename
fileContent=whats in the filename

这大约是我想要做的,但它永远不会将文件名传递给 file2。

【问题讨论】:

  • 你的问题是:imort 不是有效的 Python 代码,whats in the filename 也不是。修复这些问题,您的语法错误就会消失。

标签: python import


【解决方案1】:

这似乎是你第一次接触 Python,也许是编程,所以我建议你在 StackOverflow 上就特定事件提出问题,提供尽可能多的细节,并始终包含你编写的所有代码.

无论如何, Python 的 import 语句是一种允许一个模块访问另一个模块的实用程序。因此,例如,如果我这样定义文件 general.py:

def print_hello_world():
    print "Hello World Stack Overflow!"

在任何其他文件中,包含代码:

import general
general.print_hello_world

会给出输出“Hello World Stack Overflow!”

另外,这里是导入的参考指南:https://docs.python.org/3/reference/import.html

【讨论】:

    【解决方案2】:

    您在这里拥有的是循环导入。 file1 导入 file2:

    import file2
    

    file2 导入 file1:

    from file1 import filename
    

    这是一个禁忌。 file1 告诉 Python 导入 file2,它告诉 Python 导入 file1,它告诉 Python 导入 file2……等等。

    当您运行此代码时究竟会发生什么?你收到ImportError: cannot import name <blah> 了吗?是否有任何理由需要将代码放在两个单独的文件中,或者可以将其合并到一个文件中?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-22
      • 2017-12-28
      • 2017-09-13
      相关资源
      最近更新 更多